I am trying to get the total number of items and categorize them using case statements. 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? I included the desired outcome below.
Here's my table:
TABLE BOX1
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()
:
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);
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.