| | |
Complex Query Help
Please support our MS SQL advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Jan 2007
Posts: 9
Reputation:
Solved Threads: 0
I need to write a query that pulls out Zip codes by the first three characters, so I started with this:
But I would also like to query out the zips by those substrings I pulled out, so that would be like this:
And I need the result to be unique, and also I would like to sum all of the values that are in a column called [AvailNums] which belong to zip codes that have similar beginnings.
In other words if there are four zip codes like so:
Zip AvailNums
97301 425
97305 345
12302 1236
12305 445
I would like the resultset to look like this:
Zip AvailNums
973 770
123 1681
MS SQL Syntax (Toggle Plain Text)
SELECT SUBSTRING(Zip, 1, 3) FROM AvailHomeZips AS tZip
MS SQL Syntax (Toggle Plain Text)
SELECT Zip FROM AvailHomeZips WHERE Zip LIKE @Zip + "%"
In other words if there are four zip codes like so:
Zip AvailNums
97301 425
97305 345
12302 1236
12305 445
I would like the resultset to look like this:
Zip AvailNums
973 770
123 1681
I don't know how exactly MS SQL behaves, but here is an equivalen in MySQL. Try to modify this to your needs:
sql Syntax (Toggle Plain Text)
SELECT SUBSTRING(zip, 1, 3) as ZIP, sum(AvailNums) as SUM FROM AvailHomeZips GROUP BY ZIP;
Last edited by ~s.o.s~; Jun 23rd, 2007 at 6:41 am.
I don't accept change; I don't deserve to live.
I had tried the query pasted by me in my previous post on MySQL so I don't know what went wrong when the same was ported to MS SQL.
Try this:
I guess MS SQL doesn't take into consideration the case hence the results. Post if it works or not.
Try this:
sql Syntax (Toggle Plain Text)
SELECT SUBSTRING(zip, 1, 3) as Z, sum(AvailNums) as SUM FROM AvailHomeZips GROUP BY Z;
I guess MS SQL doesn't take into consideration the case hence the results. Post if it works or not.
I don't accept change; I don't deserve to live.
If what you say is true, then try out this one:
sql Syntax (Toggle Plain Text)
SELECT SUBSTRING(zip, 1, 3), sum(AvailNums) FROM AvailHomeZips GROUP BY SUBSTRING(zip, 1, 3);
I don't accept change; I don't deserve to live.
![]() |
Similar Threads
Other Threads in the MS SQL Forum
- Previous Thread: insert multiple rows in database
- Next Thread: Stored procedure with Dynamic columns?
| Thread Tools | Search this Thread |






