所以我在这个SQL查询中被困了一个星期。
我有下表:
CLIENT | DELIV. C. |
---------------------
10 | 200 |
10 | 700 |
10 | 700 |
40 | 200 |
30 | 300 |
20 | 400 |
30 | 400 |
50 | 900 |
我需要产生以下结果
CLIENTS W/1 DELIV C|CLIENTS W/ 2 DELIV C|CLIENTS W/ 3 DELIV C| CLIENTS 4+ DELIV C|
----------------------------------------------------------------------------------
3 | 1 | 1 | 0 |
提前致谢。
答案 0 :(得分:2)
这是聚合上的聚合(第二个是进行透视):
select sum(NumDeliveries = 1) as "CLIENTS W/1 DELIV C",
sum(NumDeliveries = 2) as "CLIENTS W/2 DELIV C",
sum(NumDeliveries = 3) as "CLIENTS W/3 DELIV C",
sum(NumDeliveries > 3) as "CLIENTS 4+ DELIV C"
from (select client, count(*) as NumDeliveries
from t
group by client
) t;
在大多数其他数据库中,您可以使用case
作为:
select sum(case when NumDeliveries = 1 then 1 else 0 end) as "CLIENTS W/1 DELIV C",
MySQL也支持这种标准符号。
编辑:
子查询正在计算每个客户的交付数量。这是非常基本的SQL,它是您想要转动的(即,从行移动到列)。
外部查询通过使用条件聚合来旋转数据。表达式:
sum(NumDeliveries = 2) as "CLIENTS W/2 DELIV C",
评估如下:
当条件为真时,表达式NumDeliveries = 2
返回1,否则返回false。然后总和是这个为真的次数的总和。