使用sql计算给定月份的出现案例总数

时间:2017-10-19 08:39:23

标签: sql sql-server

输出应该是这样的

S/NO.   MONTH   | CIVIL |CRIMINAL | TOTAL

1   JANUARY 
2   FEBRUARY    
3   MARCH   
4   APRIL
5   MAY     
6   JUNE    
7   JULY    
8   AUGUST  
9   SEPTEMBER   
10  OCTOBER 
11  NOVEMBER    
12  DECEMBER    
    GRAND TOTAL


SELECT JUD_CASE_FILED_MONTH , (SELECT COUNT(JUD_CASE_CATEGORY) FROM[hospitaldb].[dbo].[CF_CASE_REGISTER] WHERE JUD_CASE_CATEGORY ='CIVIL CASES' AND JUD_CASE_FILED_MONTH LIKE '%BER%') as CIVIL,(SELECT COUNT(JUD_CASE_CATEGORY) FROM[hospitaldb].[dbo].[CF_CASE_REGISTER] WHERE JUD_CASE_CATEGORY ='CRIMIMAL CASES'AND JUD_CASE_FILED_MONTH LIKE '%BER%') as CRIMINAL
FROM [hospitaldb].[dbo].[CF_CASE_REGISTER]
GROUP BY JUD_CASE_FILED_MONTH
Union all
select 'SUM' JUD_CASE_CATEGORY, COUNT(JUD_CASE_CATEGORY)
from [hospitaldb].[dbo].[CF_CASE_REGISTER]

我想显示月份,案例类别(民事和刑事)以及在特定月份注册的所有案例类别的总数。获得给定月份中所有案例类别的总和和数量。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT 
  JUD_CASE_FILED_MONTH , 
  SUM(CASE WHEN JUD_CASE_CATEGORY = 'CIVIL CASES'    THEN 1 ELSE 0 END AS 'CIVIL CASES',
  SUM(CASE WHEN JUD_CASE_CATEGORY = 'CRIMIMAL CASES' THEN 1 ELSE 0 END AS 'CRIMIMAL CASES',
  COUNT(*) AS Total
FROM [hospitaldb].[dbo].[CF_CASE_REGISTER]
WHERE JUD_CASE_FILED_MONTH LIKE '%BER%'
GROUP BY JUD_CASE_FILED_MONTH