1

我已经被这个 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          |
4

1 回答 1

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在大多数其他数据库中,您将使用as写出条件:

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,否则返回假。然后,总和是这种情况为真的次数的总和。

于 2013-08-02T19:06:37.573 回答