[英]How to use count using case statements
I am trying to get the total number of items and categorize them using case statements. 我正在尝试获取项目总数,并使用case语句对它们进行分类。 However, I keep getting the items (which are now categorized as "inv") repeated (eg "clothes" is repeated 4 times, each with a count of 1 instead of just once with the total count of 4) - how do I get rid of that?
但是,我一直在重复重复这些项(现在归为“ inv”)(例如,“衣服”重复了4次,每次计数为1,而不是总数为4的一次)-如何获得摆脱那个? I included the desired outcome below.
我在下面列出了期望的结果。
Here's my table: 这是我的桌子:
TABLE BOX1 表框1
ITEM_NO ITEM DATE
===================================
3130C MARVEL_SHIRT 01-JAN-17
1845C SPONGEBOB_BOXERS 03-DEC-18
A900C CK_COAT 04-DEC-18
A988C RIDER_JEANS 11-JAN-19
L350T BARBIE 23-NOV-18
L129T LEGO 09-OCT-18
LXZYT BATMAN_FIG1 12-JAN-19
My code: 我的代码:
select (case substr (item_no,5,1)
when 'C' then 'clothes'
when 'T' then 'toys' else 'misc' end) inv,
count(item_no) total
from box1 where date <= sysdate
group by item
Desired Outcome: 期望的结果:
INV TOTAL
===============
CLOTHES 4
TOYS 3
You need to group by your categories. 您需要按类别分组。
SELECT CASE substr(item_no, 5, 1)
WHEN 'C' THEN
'clothes'
WHEN 'T' THEN
'toys'
ELSE
'misc'
END inv,
count(item_no) total
FROM box1
WHERE date <= sysdate
GROUP BY CASE substr(item_no, 5, 1)
WHEN 'C' THEN
'clothes'
WHEN 'T' THEN
'toys'
ELSE
'misc'
END;
Becasue of the nature of your expression, you only need to aggregate on substr()
: 由于表达式的性质,您只需要在
substr()
上进行聚合:
select (case substr(item_no, 5, 1)
when 'C' then 'clothes'
when 'T' then 'toys'
else 'misc'
end) inv,
count(item_no) total
from box1
where date <= sysdate
group by substr(item_no, 5, 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.