SELECT CASE
WHEN age BETWEEN 1 AND 25 THEN '1-25'
WHEN age BETWEEN 26 AND 35 THEN '26-35'
WHEN age BETWEEN 36 AND 45 THEN '36-45'
WHEN age BETWEEN 46 AND 55 THEN '46-55'
WHEN age >= 56 THEN '56+'
END AS Age_Range,
Sum(CASE
WHEN gender = 'Male' THEN 1
ELSE 0
END) AS "M Count",
Sum(CASE
WHEN gender = 'Female' THEN 1
ELSE 0
END) AS "F Count",
Sum(CASE
WHEN gender = 'Unk' THEN 1
ELSE 0
END) AS "Unk Count"
FROM dm_owner.v_individualbrand
WHERE Trunc(txn_date) BETWEEN '01-JAN-18' AND '31-DEC-18'
AND brandcode = 'HT'
GROUP BY CASE
WHEN age BETWEEN 1 AND 25 THEN '1-25'
WHEN age BETWEEN 26 AND 35 THEN '26-35'
WHEN age BETWEEN 36 AND 45 THEN '36-45'
WHEN age BETWEEN 46 AND 55 THEN '46-55'
WHEN age >= 56 THEN '56+'
END
ORDER BY age_range;
我正尝试增加2列,分别是交易数和总销售额。我的桌子应该像这样:
答案 0 :(得分:1)
您要扩展条件聚合。您的当前计数似乎是交易计数,除非那是表中的单独列。
查询如下:
SELECT (CASE WHEN age BETWEEN 1 AND 25 THEN '1-25'
WHEN age BETWEEN 26 AND 35 THEN '26-35'
WHEN age BETWEEN 36 AND 45 THEN '36-45'
WHEN age BETWEEN 46 AND 55 THEN '46-55'
WHEN age >= 56 THEN '56+'
END) as Age_Range,
Sum(CASE WHEN gender = 'Male' THEN 1 ELSE 0 END) AS "M Count",
Sum(CASE WHEN gender = 'Male' THEN sales ELSE 0 END) AS "M Sales",
Sum(CASE WHEN gender = 'Female' THEN 1 ELSE 0 END) AS "F Count",
Sum(CASE WHEN gender = 'Female' THEN sales ELSE 0 END) AS "F Sales",
Sum(CASE WHEN gender = 'Unk' THEN 1 ELSE 0 END) AS "Unk Count"
Sum(CASE WHEN gender = 'Unk' THEN sales ELSE 0 END) AS "Unk Sales"
FROM dm_owner.v_individualbrand
WHERE txn_date >= DATE '2018-01-01' AND
txn_date < DATE '2019-01-01' AND
brandcode = 'HT'
GROUP BY (CASE WHEN age BETWEEN 1 AND 25 THEN '1-25'
WHEN age BETWEEN 26 AND 35 THEN '26-35'
WHEN age BETWEEN 36 AND 45 THEN '36-45'
WHEN age BETWEEN 46 AND 55 THEN '46-55'
WHEN age >= 56 THEN '56+'
END)
ORDER BY MIN(age);