问题
first time poster and just looking for some guidance on writing a case statement. I'd like to pull the following from a single table
total orders by week cancelled orders by week % of orders cancelled
I did some reading on case statements, but couldn't find exactly what I was looking for. I assume the case statement would be something along the lines of
"case when order = 'cancelled' THEN count orders", but I also know that's wrong, so just looking for some assistance.
Thanks in advance!
-ET
回答1:
The usual ways of doing a count of partial rows is to do a count
query with a where clause to select which rows. Each of these can be outer joined with other similar queries.
The way to do it in one select using case
is to put the case
inside a sum
:
SELECT SUM(case when order = 'cancelled' THEN 1 ELSE 0 END) AS cancelled, ...
回答2:
You should probably build a nested query for this: First, build you query to get things sorted by week.
SELECT orderID, orderStatus, DATEPART(week, orderDate) as orderWeek
FROM orders
Then you can probably get a select from that as follows:
SELECT count(orderID) OVER(PARTITION BY orderWeek) AS Total
,count(orderID) OVER(PARTITION BY orderWeek, orderStatus) AS CountPerStatus
,orderWeek
FROM (SELECT orderID, orderStatus, DATEPART(week, orderDate) as orderWeek
FROM orders) a
add then finally get your totals on one row:
SELECT Total, CountPerStatus, orderWeek
FROM (
SELECT count(orderID) OVER(PARTITION BY orderWeek) AS Total
,count(orderID) OVER(PARTITION BY orderWeek, orderStatus) AS CountPerStatus
,orderWeek
FROM (
SELECT orderID, orderStatus, DATEPART(week, orderDate) as orderWeek
FROM orders
) a
) b
WHERE CountPerStatus = 'Cancelled'
This can clearly be simplified but I prefer to explicit it for better understanding. Hope it helps.
来源:https://stackoverflow.com/questions/59535043/using-case-statement-to-get-weekly-count-of-total-orders-cancelled-orders-and