简体   繁体   中英

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.

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

在此处输入图像描述

This is the required output which I'm supposed to be expected.

在此处输入图像描述

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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