假设我有这样一个销售表:
store_id industry_id cust_id amount gender age
1 100 1000 1.00 M 20
2 100 1000 2.05 M 20
3 100 1000 3.15 M 20
4 200 2000 5.00 F 30
5 200 2000 6.00 F 30
以下是生成此表的代码:
CREATE TABLE t1(
store_id int,
industry_id int,
cust_id int,
amount float,
gender char,
age int
);
INSERT INTO t1 VALUES(1,100,1000,1.00, 'M',20);
INSERT INTO t1 VALUES(2,100,1000,2.05, 'M',20);
INSERT INTO t1 VALUES(3,100,1000,3.15, 'M',20);
INSERT INTO t1 VALUES(4,200,2000,5.00, 'F',30);
INSERT INTO t1 VALUES(5,200,2000,6.00, 'F',30);
假设我们想找出每个年龄/性别组合的消费总额。像这样:
gender age total_amount
M 20 6.20
F 30 11.00
以下代码不起作用(它抛出“操作数应包含1列”错误):
SELECT
('M','F') as gender
, (20,30) as age
, (SUM(CASE WHEN gender='M' AND age=20 THEN amount END)
, SUM(CASE WHEN gender='F' AND age=30 THEN amount END)) as total_amount
FROM t1;
最好的办法是什么?
3条答案
按热度按时间33qvvth11#
可能是这样的:
lxkprmvk2#
使用此选项:
dfddblmv3#
我们要找出每个年龄/性别组合的支出总额
我想你只是想:
db小提琴演示: