sql_join_case when示例_統計金額
統計每個time下每個type的金額
select
time,
type
sum(price)
from purchase a
join
purchase_commodity b
where a.user=b.user
group by time,type
統計食品(飲料,盒飯,麪包)和非食品(化妝品)的結賬金額
select
flag,
sum(payment)
from
(
select
case b.type
when '化妝品' then '1'
else '0' end flag,
payment
from purchase a
join
purchase_commodity b
where a.user=b.user
)
group by flag;
請寫出查詢代碼,統計每5歲爲一個年齡層,每個年齡層的人數(20歲到39歲的會員分開每5歲爲一個年齡層,其他年齡分類到‘其他年齡’)
select
flag,
count(1)
(
select
CASE WHEN age >=20 and age <25 THEN '1'
CASE WHEN age >=25 and age <30 THEN '2'
CASE WHEN age >=30 and age <35 THEN '3'
CASE WHEN age >=35 and age <40 THEN '4'
ELSE '其他年齡' END flag
from
(
--獲取年齡
to_char(to_date(sysdate,'yyyy'))-substr(birthday,1,4) as age
from t_user
)
group by flag