为什么我得到2个不同列的相同总值

时间:2012-04-20 19:47:02

标签: sql

我需要有人纠正以下声明。提前谢谢。

SELECT CATEGORY
--WHAT PERIOD?
,'P3' AS PERIOD
,'2013' AS FISCALYEAR        
,COUNT(CASE SecurityLayer WHEN 'dblayer' THEN SecurityLayer ELSE '' END) DB_SEC_COUNT         
,COUNT(CASE SecurityLayer WHEN 'Applayer' THEN SecurityLayer ELSE '' END) APP_SEC_COUNT  
FROM [db_eCAM].[dbo].[tbl_SecChecks]  
GROUP BY CATEGORY

2 个答案:

答案 0 :(得分:2)

您是否尝试返回每个匹配的#次?然后使用

SELECT CATEGORY
--WHAT PERIOD?
,'P3' AS PERIOD
,'2013' AS FISCALYEAR  
,SUM(CASE SecurityLayer WHEN 'dblayer' then 1 else 0 end) AS DB_SEC_COUNT
,SUM(CASE SecurityLayer WHEN 'Applayer' then 1 else 0 end) AS APP_SEC_COUNT
FROM [db_eCAM].[dbo].[tbl_SecChecks]  
GROUP BY CATEGORY

试试。

答案 1 :(得分:2)

不要对列进行计数,而是尝试对其进行求和(否则,无论其值如何,每行仍将被计数):

SELECT CATEGORY
--WHAT PERIOD?
,'P3' AS PERIOD
,'2013' AS FISCALYEAR        
,SUM(CASE SecurityLayer WHEN 'dblayer' THEN 1 ELSE 0 END) DB_SEC_COUNT         
,SUM(CASE SecurityLayer WHEN 'Applayer' THEN 1 ELSE 0 END) APP_SEC_COUNT  
FROM [db_eCAM].[dbo].[tbl_SecChecks]  
GROUP BY CATEGORY