sql:组合上的和

mspsb9vt  于 2021-06-24  发布在  Hive
关注(0)|答案(3)|浏览(329)

假设我有这样一个销售表:

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;

最好的办法是什么?

33qvvth1

33qvvth11#

可能是这样的:

SELECT gender
       , age 
       , SUM(amount) as total_amount
FROM t1
where (gender = 'M' and age = 20)
      or (gender = 'F' and age = 30)
group by gender, age
lxkprmvk

lxkprmvk2#

使用此选项:

Select gender, age, sum(amount ) as total_amout
from t1
group by gender,age
dfddblmv

dfddblmv3#

我们要找出每个年龄/性别组合的支出总额
我想你只是想:

select gender, age, sum(amount) total_amount
from t1
group by gender, age

db小提琴演示:

gender | age | total_amount
:----- | --: | :-----------
M      |  20 | 6.2         
F      |  30 | 11

相关问题