MySQL Case语句根据count()按列分组

时间:2015-09-08 15:00:02

标签: mysql

这是我的查询

select distinct part_no, customer, tran_type
from (select customer, part_no, tran_type
      from stock qi
      union all
      select customer, part_no, tran_type
      from stock
            having count(customer)=2
     ) t
HAVING customer  '' AND tran_type ='Dispatch'
ORDER BY part_no

其中输出的内容如下:

part_no         customer    transaction
0005843309      DL004       Dispatch
0005915052      SC014       Dispatch
0006543119      DL004       Dispatch
0006555024      SC014       Dispatch
0006559509      SC014       Dispatch
0008085150      SC014       Dispatch
0030117107      XR384       Dispatch
00456           TZ030       Dispatch
00BK0008A02     KS004       Dispatch
00BK0011A02     A0144       Dispatch
00BK0015A02     X109        Dispatch
0200551824      A0308       Dispatch
0200551824      AC400       Dispatch
0200551824      MI020       Dispatch
023131          SI019       Dispatch
0270007125      E0098       Dispatch
07H890W407G1    SG006       Dispatch
09CB5001A01SP   AS032       Dispatch
09E806W980Z1    VS003       Dispatch
09F103Y398G1+MODM13C    TF003   Dispatch
100-0QTC85-000  A0113       Dispatch
100-0QTC85-000  A0512       Dispatch
100-0QTC85-000  C0118       Dispatch
100-0QTC85-000  C0553       Dispatch
100-0QTC85-000  P0269       Dispatch
100-0QTC85-000  S0023       Dispatch
100-0QTC85-000  S0618       Dispatch
106-RELAYS      SUP03       Dispatch
11266           A0512       Dispatch
11337           C0553       Dispatch
115-1024-1828BZ A0077       Dispatch

我想获得每个part_no的列表,其中只有一个客户与之相关 每个人只有2个,然后是其他任何东西都会分开 我认为会完成这项工作的案例陈述,但它没有。

有人可以帮我调整查询以实现输出。非常感谢

3 个答案:

答案 0 :(得分:0)

您需要使用GROUP BY part_no,因此它会计算每个部分的客户数量。

SELECT part_no
FROM stock
GROUP BY part_no
HAVING COUNT(DISTINCT customer) = 1

答案 1 :(得分:0)

也许这会有所帮助

SELECT part_no, COUNT(DISTINCT customer), "A" category
FROM stock
GROUP BY part_no
HAVING COUNT(DISTINCT customer) = 1
UNION ALL 
SELECT part_no, COUNT(DISTINCT customer), "B" category
FROM stock
GROUP BY part_no
HAVING COUNT(DISTINCT customer) = 2
UNION ALL
SELECT part_no, COUNT(DISTINCT customer), "C" category
FROM stock
GROUP BY part_no
HAVING COUNT(DISTINCT customer) > 2

答案 2 :(得分:0)

使用子查询获取每个part_no

的客户数量
SELECT part_no, customer, tran_type
FROM stock
INNER JOIN
(
    SELECT part_no, COUNT(customer) AS cust_count
    FROM stock
    GROUP BY part_no
) sub0
ON stock.part_no = sub0.part_no
ORDER BY IF(sub0.cust_count <= 2, sub0.cust_count, 3)