SQL - 为AVG和COUNT分组段

时间:2017-11-18 23:07:24

标签: sql sql-server

对于Parking Citations的数据库,我编写了以下语法,以显示属于某些ViolFine参数的每个Citation的段:

SELECT Citation, Make, ViolCode, ViolDate, ViolFine
    ,CASE 
        WHEN ViolFine BETWEEN 0.00 AND 50.00 THEN '01. $0.00 - $50.00'
        WHEN ViolFine BETWEEN 50.01 AND 100.00 THEN '02. $50.01 - $100.00'
        WHEN ViolFine > 100 THEN '03. larger than $100.00'  
      END AS ViolFineSegments
FROM dbo.ParkingCitations
ORDER BY ViolDate DESC

现在我想获得GROUP上面定义的每个段的结果。我使用了以下内容,但似乎是将每个不同的ViolFine与相应的引用总数以及分段参数分组:

SELECT AVG(ViolFine) AS AvgFine, COUNT(Citation) AS NumberViolations
    ,CASE 
        WHEN AVG(ViolFine) BETWEEN 0.00 AND 50.00 THEN '01. $0.00 - $50.00'
        WHEN AVG(ViolFine) BETWEEN 50.01 AND 100.00 THEN '02. $50.01 - $100.00'
        WHEN AVG(ViolFine) > 100 THEN '03. larger than $100.00' 
      END AS ViolFineSegments
FROM dbo.ParkingCitations
GROUP BY  ViolFine
ORDER BY ViolFine

基本上,我希望每个组段只需要三行,显示平均引文和每个分组的计数,我确定如何继续。

我也尝试了下面的内容,但是只列出了一个长行,我想要三个单独的行。

SELECT COUNT(CASE WHEN ViolFine BETWEEN 0.00 AND 50.00 THEN '01. $0.00 - $50.00' END) '0-50',
       COUNT(CASE WHEN ViolFine BETWEEN 50.01 AND 100.00 THEN '02. $50.01 - $100.00' END) as '50-100',
       COUNT(CASE WHEN ViolFine > 100 THEN '03. larger than $100.00' END) as '>100',
       AVG(CASE WHEN ViolFine BETWEEN 0.00 AND 50.00 THEN ViolFine END) as '0-50',
       AVG(CASE WHEN ViolFine BETWEEN 50.01 AND 100.00 THEN ViolFine END) as '50-100',
       AVG(CASE WHEN ViolFine > 100 THEN ViolFine END) as '>100'
FROM dbo.ParkingCitations;

2 个答案:

答案 0 :(得分:2)

使用case表达式进行细分,并按该表达式分组,以获得平均值和计数。

SELECT 
CASE WHEN ViolFine BETWEEN 0.00 AND 50.00 THEN '01. $0.00 - $50.00'         
     WHEN ViolFine BETWEEN 50.01 AND 100.00 THEN '02. $50.01 - $100.00' 
     WHEN ViolFine > 100 THEN '03. larger than $100.00' 
END as fine_segment
,COUNT(*) as fine_count
,AVG(1.0*ViolFine) as avg_fine
FROM dbo.ParkingCitations
GROUP BY CASE WHEN ViolFine BETWEEN 0.00 AND 50.00 THEN '01. $0.00 - $50.00'         
              WHEN ViolFine BETWEEN 50.01 AND 100.00 THEN '02. $50.01 - $100.00' 
              WHEN ViolFine > 100 THEN '03. larger than $100.00' 
         END

答案 1 :(得分:2)

我面前没有编辑器,但你可以在你拥有的每个案例陈述中使用UNION ALL

    SELECT AVG(ViolFine) AS AvgFine, COUNT(Citation) AS NumberViolations, AVG(ViolFine) AS [01. $0.00 - $50.00]
    FROM dbo.ParkingCitations
    GROUP BY  ViolFine
    HAVING AVG(ViolFine) BETWEEN 0.00 AND 50.00
    UNION ALL
    SELECT AVG(ViolFine) AS AvgFine, COUNT(Citation) AS NumberViolations, AVG(ViolFine) AS [02. $50.01 - $100.00]    
    ...