Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
almeidag
Starting Member
2 Posts |
Posted - 2010-07-14 : 10:45:22
|
Hi all,I have this simple query:SELECT StateId, count(*) FROM REQUISITION GROUP BY StateIdORDER BY StateIdThis returns:3 19 24So I have 1 row with the StateId = 3 and 24 rows with StateId = 9. So far so good.Now comes the tricky part:I need to build a query to return this:1 02 03 14 05 06 07 08 09 24I need to ALWAYS return 9 rows even if not all StateId are present in the main table. I was wondering if this is possible using a query or if I have to use programming to maniulate the result set.thanks in advance |
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2010-07-14 : 11:09:44
|
DECLARE @Table Table (Stateid smallint)INSERT INTO @TABLESelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALLSelect 1 UNION ALL Select 2 UNION ALLSelect 2 UNION ALLSelect 2 UNION ALLSelect 2 Select spt.number,isnull(count(stateid),0) as Recsfrom master..spt_values sptleft join @table ton spt.number = t.stateidwhere spt.[type] = 'P' and spt.number between 0 and 9group by spt.numberJimEveryday I learn something that somebody else already knew |
 |
|
almeidag
Starting Member
2 Posts |
Posted - 2010-07-14 : 11:28:29
|
Thanks jimf, that's exactly what I was looking for.regards |
 |
|
|
|
|