获取GROUP BY记录子集的计数

时间:2018-02-28 01:28:25

标签: sql sql-server count subquery

我有一个邮件分类帐表,我试图查询返回百分比。我正在做一个GROUP BY来获取基于order_no,county和zip_code的唯一记录。

SELECT, COUNT(*) as TotalMailed, COUNT(*) (WHERE Returned = 1) as ReturnedMailed, Order_No, Zip_Code,County
FROM MailLedger
GROUP BY Order_No, Zip_Code, County

我正在获取每个记录分组的正确计数,但是我需要获取已将Returned设置为true的分组记录子集的计数。

我正在运行SQL Server,所以我确实可以使用OVER和PARTITION,但是,我也很想知道在Postgres / MySQL中处理它的正确方法。

1 个答案:

答案 0 :(得分:2)

在SQL Server中,您可以使用条件聚合。我通常使用SUM(CASE . . . )执行此操作:

SELECT COUNT(*) as TotalMailed,
       SUM(CASE WHEN Returned = 1 THEN 1 ELSE 0 END) as ReturnedMailed,
       Order_No, Zip_Code, County
FROM MailLedger
GROUP BY Order_No, Zip_Code, County;

如果Returned仅采用值1和0 / NULL,则可以执行以下操作:

SELECT COUNT(*) as TotalMailed,
       SUM(Returned) as ReturnedMailed,
       Order_No, Zip_Code, County
FROM MailLedger
GROUP BY Order_No, Zip_Code, County;