日期:2014-05-18 浏览次数:20636 次
SELECT NAME ,AVG(A) AS A ,AVG(B) AS B ,AVG(C) AS C ,SUM(CASE WHEN D<=4 THEN 1 ELSE 0 END)*100.0/SUM(1) AS [<=4] ,SUM(CASE WHEN >4 THEN 1 ELSE 0 END)*100.0/SUM(1) AS [>4] FROM A GROUP BY NAME UNION ALL SELECT NAME = '总计' ,AVG(A) AS A ,AVG(B) AS B ,AVG(C) AS C ,SUM(CASE WHEN D<=4 THEN 1 ELSE 0 END)*100.0/SUM(1) AS [<=4] ,SUM(CASE WHEN >4 THEN 1 ELSE 0 END)*100.0/SUM(1) AS [>4] FROM A
------解决方案--------------------
--> 测试数据:[ta] IF OBJECT_ID('[ta]') IS NOT NULL DROP TABLE [ta] GO CREATE TABLE [ta]([name] VARCHAR(3),[a] INT,[b] INT,[c] INT,[d] INT) INSERT [ta] SELECT '001',1,2,3,4 UNION ALL SELECT '001',5,6,7,4 UNION ALL SELECT '001',2,3,4,8 UNION ALL SELECT '002',1,2,3,4 UNION ALL SELECT '002',3,2,2,5 UNION ALL SELECT '003',2,2,2,4 --------------开始查询-------------------------- SELECT [name], AVG([a] * 1.0), AVG([b] * 1.0), AVG([c] * 1.0), SUM(CASE WHEN [d]<=4 THEN 1 ELSE 0 END) * 100.0 / COUNT([name]) FROM [ta] GROUP BY [name] WITH ROLLUP ----------------结果---------------------------- /* name ---- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- 001 2.666666 3.666666 4.666666 66.666666666666 002 2.000000 2.000000 2.500000 50.000000000000 003 2.000000 2.000000 2.000000 100.000000000000 NULL 2.333333 2.833333 3.500000 66.666666666666 (4 行受影响) */
------解决方案--------------------
--> 测试数据:[ta] IF OBJECT_ID('[ta]') IS NOT NULL DROP TABLE [ta] GO CREATE TABLE [ta]([name] VARCHAR(3),[a] INT,[b] INT,[c] INT,[d] INT) INSERT [ta] SELECT '001',1,2,3,4 UNION ALL SELECT '001',5,6,7,4 UNION ALL SELECT '001',2,3,4,8 UNION ALL SELECT '002',1,2,3,4 UNION ALL SELECT '002',3,2,2,5 UNION ALL SELECT '003',2,2,2,4 --------------开始查询-------------------------- SELECT [name], AVG([a] * 1.0), AVG([b] * 1.0), AVG([c] * 1.0), SUM(CASE WHEN [d]<=4 THEN 1 ELSE 0 END) * 100.0 / COUNT([name]) FROM [ta] GROUP BY [name] UNION ALL SELECT '统计', AVG([a] * 1.0), AVG([b] * 1.0), AVG([c] * 1.0), SUM(CASE WHEN [d]<=4 THEN 1 ELSE 0 END) * 100.0 / COUNT([name]) FROM [ta] ----------------结果---------------------------- /* name ---- --------------------------------------- --------------------------------------- --------------------------------------- ----------------