我使用下面的SQL查询形成了下表。
STATE count(goo) AVG_SAL count(SCOPE) AVG_SAL count(FB) AVG_SAL count(PAL) AVG_SAL
KN 1 5500 -- -- -- -- -- --
IN -- -- 1 6000 1 3999 -- --
AR 1 7000 -- -- 1 8250 -- --
CL 1 6000 -- -- -- -- 1 4500
SELECT
state,
GooCount,
GooCount / Total AS AVG_GOO,
sCOPECount,
SCOPECount / Total AS AVG_SCOPE,
FBCOunt,
FBCount / Total AS AVG_FB,
PALCount,
PALCount / Total AS AVG_PAL
FROM
(
select
state,
SUM(CASE WHEN COMPANY_NAME = 'GOO' THEN 1 ELSE 0 END) AS GooCount,
SUM(CASE WHEN COMPANY_NAME = 'SCOPE' THEN 1 ELSE 0 END) AS SCOPECount,
SUM(CASE WHEN COMPANY_NAME = 'FB' THEN 1 ELSE 0 END) AS FBCount,
SUM(CASE WHEN COMPANY_NAME = 'PAL' THEN 1 ELSE 0 END) AS PALCount,
COUNT(*) AS total
from company_details
where company_status = 'OPEN'
group by state order by state
) AS sub;
但是我想形成这样的输出。
STATE count(goo) AVG_SAL count(SCOPE) AVG_SAL count(FB) AVG_SAL count(PAL) AVG_SAL
KN 1 5500 -- -- -- -- -- --
IN -- -- 1 6000 1 3999 -- --
AR 1 7000 -- -- 1 8250 -- --
CL 1 6000 -- -- -- -- 1 4500
Total 3 18500 1 6000 2 12249 1 4500
我想做一个明智的计数。
答案 0 :(得分:1)
看看Group + Rollup。
http://msdn.microsoft.com/en-us/library/ms189305%28v=sql.90%29.aspx