2016-03-25 64 views
-1

這是我的問題。我想找到重複的「代碼IFLS」,並獲得不同的倉庫,我得到這個重複的代碼用於查找重複並獲取其他值的SQL查詢

這是表的樣子:

| code ifls | warehouse | 
| 4013 |  1 | 
| 4013 |  2 | 
| 4013 |  3 | 
| 4014 |  4 | 
| 4014 |  5 | 
| 4015 |  5 | 

結果應該是這樣的:

| code ifls | warehouse | warehouse | warehouse | 
| 4013 |  1  |  2  |  3  | 
| 4014 |  4  |  5  |   | 

我試過了請求,但沒有成功......

SELECT code ifls as ifls, (SELECT warehouse FROM catalogue WHERE code ifls= ifls) 
FROM catalogue GROUP BY code ifls HAVING COUNT(code ifls) > 1 

你會怎樣表達THI s在SQL查詢中?

+0

http://stackoverflow.com/questions/36177816/combine-multiple-child-rows-into-one-row-mysql-without-hardcoding-or-min-max-val/36178292#36178292 –

+0

你可以' t很容易有這樣的動態數量的列。是否有您需要的最大數量的列,或者您是否按照需要生成列? –

回答

0

GROUP_CONCAT()可能是做你想要做什麼,而不使用動態複雜的事情簡單的方法列;

SELECT `code ifls`, GROUP_CONCAT(warehouse) warehouses 
FROM myTable 
GROUP BY `code ifls` 
HAVING COUNT(*) > 1 

An SQLfiddle to test with

它基本上爲每個code ilfs提供逗號分隔的倉庫列表,但HAVING將其限制爲具有多個倉庫的行。

+1

太棒了!這正是我需要的! Thx Joachim! – Guibrid

0

您可以使用子查詢和GROUP_CONCAT

select `code ifls`, group_concat(warehouse) 
from table 
where `code ifls` in (
    select `code ifls`, count(*) 
    from table 
    group by `code ifls` 
    having count(*) > 1 
) 
group by `code ifls` 
0

這裏是你的代碼 -

SELECT `code ifls`, 
SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',1) AS warehouse_1, 
IF((LENGTH(GROUP_CONCAT(warehouse)) - LENGTH(GROUP_CONCAT(warehouse SEPARATOR ''))) < 1,'',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',2),',',-1)) AS warehouse_2, 
IF((LENGTH(GROUP_CONCAT(warehouse)) - LENGTH(GROUP_CONCAT(warehouse SEPARATOR ''))) < 2,'',SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',-1)) AS warehouse_3 
FROM `catalogue` 
GROUP BY `code ifls`;