SQL - 使用CASE和AVG

时间:2017-11-18 21:36:51

标签: 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

现在我想列出每个细分的引文数和平均引文数。我使用了以下内容,但它似乎只列出了每个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

基本上,我只想要基于细分的三行,我不知道如何继续。

2 个答案:

答案 0 :(得分:3)

CASE必须是聚合函数的参数。我想你想要:

SELECT AVG(ViolFine) AS AvgFine, COUNT(Citation) AS NumberViolations,
       AVG(CASE WHEN ViolFine BETWEEN 0.00 AND 50.00 THEN ViolFine END) as [01. $0.00 - $50.00],
       AVG(CASE WHEN ViolFine BETWEEN 50.01 AND 100.00 THEN ViolFine END) as [02. $50.01 - $100.00],
       AVG(CASE WHEN ViolFine > 100 THEN ViolFine END) as [03. larger than $100.00]
FROM dbo.ParkingCitations;

这将返回一行,包含五列。对于这些数字,你可以这样做:

SELECT COUNT(Citation) AS NumberViolations,
       SUM(CASE WHEN ViolFine BETWEEN 0.00 AND 50.00 THEN 1 ELSE 0 END) as cnt_000_050,
       SUM(CASE WHEN ViolFine BETWEEN 50.01 AND 100.00 THEN 1 ELSE 0 END) as cnt_050_100,
       SUM(CASE WHEN AVG(ViolFine) > 100 THEN 1 ELSE 0 END) as cnt_100pl,
       AVG(ViolFine) AS AvgFine, 
       AVG(CASE WHEN ViolFine BETWEEN 0.00 AND 50.00 THEN ViolFine END) as avg_000_050,
       AVG(CASE WHEN ViolFine BETWEEN 50.01 AND 100.00 THEN ViolFine END) as avg_050_100
       AVG(CASE WHEN ViolFine > 100 THEN ViolFine END) as avg_100pl
FROM dbo.ParkingCitations;

答案 1 :(得分:0)

  

现在我想列出引用次数和每个细分的平均引用次数。

如果按段进行,那么您需要按ViolFineSegments列进行分组。您请求的聚合是计数和平均值(ViolFine)。我会尝试使用聚合的原始代码:

SELECT 
    ViolFineSegments,
    COUNT(ViolFine) AS [Number of Citations],
    AVG(ViolFine) AS [Average Fine]
FROM 
    (SELECT 
         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) AS dT
GROUP BY 
    ViolFineSegments
ORDER BY 
    [Average Fine]