2015-09-08 64 views
0

這裏是我的查詢MySQL的case語句GROUP BY列基於計數()

 
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個,然後其他任何一個將在一個單獨的類別 一個案例陳述我認爲會完成這項工作,但它沒有。

有人可以幫我調整查詢來實現輸出。許多謝謝

回答

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 
0

您需要使用GROUP BY part_no,因此它計算每個零件的客戶數。

SELECT part_no 
FROM stock 
GROUP BY part_no 
HAVING COUNT(DISTINCT customer) = 1 
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)