- 爱易网页
-
MSSQL教程
- 分组查询的有关问题
日期:2014-05-19 浏览次数:20642 次
分组查询的问题
表A; 表B:
ID Type Name TypeID TypeName
1 R001 AS R001 示例1
2 R001 SA R002 示例2
3 R002 SA R003 示例3
4 R003 AS R004 示例4
查询结果:
TypeName AS SA
示例1 1 1
示例2 0 1
示例3 1 0
示例4 0 0
总计 2 2
请教一下,这个分组查询该怎么写
------解决方案--------------------
CREATE TABLE A
(
ID INT,
Type VARCHAR(10),
Name VARCHAR(5)
)
CREATE TABLE B
(
TypeID VARCHAR(10),
TypeName VARCHAR(10)
)
INSERT INTO A
SELECT 1, 'R001 ', 'AS ' UNION ALL
SELECT 2, 'R001 ', 'SA ' UNION ALL
SELECT 3, 'R002 ', 'SA ' UNION ALL
SELECT 4, 'R003 ', 'AS '
INSERT INTO B
SELECT 'R001 ', '示例1 ' UNION ALL
SELECT 'R002 ', '示例2 ' UNION ALL
SELECT 'R003 ', '示例3 ' UNION ALL
SELECT 'R004 ', '示例4 '
SELECT CASE GROUPING(TypeName) WHEN 1 THEN '总计 ' ELSE TypeName END TypeName,SUM([AS]),SUM(SA) FROM
(SELECT B.TypeName,[AS]=(SELECT COUNT(1) FROM A WHERE Name= 'AS ' AND Type=B.TypeID),SA=(SELECT COUNT(1) FROM A WHERE Name= 'SA ' AND Type=B.TypeID) FROM B )
AA
GROUP BY TypeName
WITH ROLLUP
--结果
TypeName
---------- ----------- -----------
示例1 1 1
示例2 0 1