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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Count

Author  Topic 

mukhan85
Starting Member

46 Posts

Posted - 2008-07-17 : 17:51:03
Hi, I have the following table:
Name Status Month
----- ====== =====
apple 1 1
apple 2 2
orange 3 1
orange 1 1
apple 2 2


RESULT
Status Number Month
------ ------ -----
1 2 1
1 0 2
1 0 3
. . .
. . .
1 0 12

2 0 1
. . .
. . .
2 0 12

Can anybody help with that?
Thank you.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-07-17 : 17:54:22
Are you using Microsoft SQL Server 2005 (or later) or are you using SQL Server 2000 (or earlier)?


E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-07-17 : 18:02:29
Never mind...
DECLARE	@Sample TABLE (Name VARCHAR(10), Status INT, Month INT)

INSERT @Sample
SELECT 'apple', 1, 1 UNION ALL
SELECT 'apple', 2, 2 UNION ALL
SELECT 'orange', 3, 1 UNION ALL
SELECT 'orange', 1, 1 UNION ALL
SELECT 'apple', 2, 2

SELECT Status,
SUM(Number) AS Number,
Month
FROM (
SELECT Status,
COUNT(*) AS Number,
Month
FROM @Sample
GROUP BY Status,
Month

UNION ALL

SELECT s.Status,
0,
v.Number
FROM @Sample AS s
INNER JOIN master..spt_values AS v ON v.Type = 'P'
WHERE v.Number BETWEEN 1 AND 12
GROUP BY s.Status,
v.Number
) AS d
GROUP BY Status,
Month
ORDER BY Status,
Month



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -