简体   繁体   English

如何将计数用于案例陈述

[英]How to use count for a case statement

I'm using the below code to get the count of every case statements which has sum inside the case statements but I'm getting the error message.我正在使用下面的代码来获取在 case 语句中具有 sum 的每个 case 语句的计数,但我收到了错误消息。

SELECT
  count(case when SUM(Orders.Sales)>10000 then 1 end) as High,
  count(case when SUM(Orders.Sales)>5000 and SUM(Orders.Sales)<9999 then 
  SUM(Orders.Sales) end) as Medium, 
  count(case when SUM(Orders.Sales)<5000 then SUM(Orders.Sales) end) as Low
FROM Orders
INNER JOIN Returns ON Orders.[Order ID] = Returns.[Order ID]

OUTPUT OUTPUT

在此处输入图像描述

This is the required output which I'm supposed to be expected.这是我应该期望的必需的 output。

在此处输入图像描述

I feel that you should be doing the outer count rollups over a subquery which aggregates by order:我觉得你应该对按顺序聚合的子查询进行外部计数汇总:

SELECT
    COUNT(CASE WHEN sales < 5000  THEN 1 END) AS Low,
    COUNT(CASE WHEN sales < 9999  THEN 1 END) AS Medium,
    COUNT(CASE WHEN sales >= 9999 THEN 1 END) AS High
FROM
(
    SELECT o.[Order ID], SUM(o.Sales) AS sales
    FROM Orders o
    INNER JOIN Returns r ON o.[Order ID] = r.[Order ID]
    GROUP BY o.[Order ID]
) t;

That being said, I don't actually know what the purpose of joining Orders to the Returns table is.话虽如此,我实际上并不知道将Orders加入Returns表的目的是什么。 If you intend to only find sales amounts from orders which have been returned, then maybe this makes sense.如果您只想从已退回的订单中查找销售额,那么这也许是有道理的。 Otherwise, maybe it doesn't make sense.否则,也许它没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM