CREATE TABLE #T
(
Name Varchar(10),
P1No Int,
P2No Int,
P3No Int,
EntryDate DateTime
)
INSERT INTO #T VALUES('Ping',11,12,13,'1/1/2009')
INSERT INTO #T VALUES('Ping',11,NULL,13,'1/1/2009')
INSERT INTO #T VALUES('Ping',NULL,NULL,NULL,'1/1/2009')
INSERT INTO #T VALUES('Ming',11,12,13,'1/1/2009')
INSERT INTO #T VALUES('Ming',11,12,13,'1/1/2009')
INSERT INTO #T VALUES('Ming',NULL,12,13,'1/1/2009')
SELECT Name,ProcedureNo,SUM(Count_no) As Total FROM
(
SELECT Name,p1No as ProcedureNo,COUNT(*) as Count_no FROM #T
GROUP BY Name,p1No
UNION
SELECT Name,p2No as ProcedureNo,COUNT(*) as Count_no FROM #T
GROUP BY Name,p2No
UNION
SELECT Name,p3No as ProcedureNo,COUNT(*) as Count_no FROM #T
GROUP BY Name,p3No
)A
WHERE ProcedureNo IS NOT NULL
Group by Name,ProcedureNo
ORDER BY Name,ProcedureNo
|