我有一张桌子
order_id user_id lunch_type box
1 1 A 5
2 1 B 1
3 1 C 3
4 2 C 4
5 2 B 2
6 3 A 7
7 4 C 6
8 4 A 1
9 5 C 9
10 5 B 2从上面的tabel开始,我想做一个新的tabel,就像这样
user_id Lunch_A Lunch_B, Lunch_C total
1 5 1 3 9
2 4 2 0 6
3 7 0 0 7我不知道如何像那样查询
发布于 2021-01-23 15:05:55
假设您现有的表是Orders,新表是OrdersSummary,因此您可以通过以下方式创建新表:
CREATE TABLE OrdersSummary
AS ( SELECT
user_id,
count(*) as total,
count(IF(lunch_type = "A", 1, NULL)) as Lunch_A,
count(IF(lunch_type = "B", 1, NULL)) as Lunch_B,
count(IF(lunch_type = "C", 1, NULL)) as Lunch_C
from Orders group by user_id
);解释:
使用CREATE table as从另一个表创建表(从中选择列)
在从现有表中选择记录时,我们根据计数对行进行分组,因此count(*)将给出use total count,我们希望对lunch_type (A,B,C)进行单独计数,因此在count表达式中,我们使用IF子句,因此它的行只有具有特定的lunch_type,才会被计数
https://stackoverflow.com/questions/65856564
复制相似问题