2014-01-23 85 views
2

,假設我們有兩個表1到n關係SQL檢查是否列值變化

group 
--+-------+ 
id|name | 
--+-------+ 
1 | GROUP1| 
2 | GROUP2| 
3 | GROUP3| 
--+-------+ 

unit 
--+-----+-----+------+ 
id|group|value|status| 
--+-----+-----+------+ 
1| 1 | 0 | 0 | 
2| 1 | 20 | 0 | 
3| 1 | 5 | 0 | 
4| 2 | 1 | 1 | 
5| 2 | 3 | 1 | 
6| 2 | 0 | 1 | 
7| 3 | 5 | 1 | 
8| 3 | 8 | 0 | 
9| 3 | 6 | 0 | 

我怎麼能知道,如果某行是該組中的獨特之處?如果不是獨一無二的,它有什麼價值? 例如:

SELECT 
    DISTINCT `group`.id, 
    `group`.name, 
    MIN(unit.value) AS 'min', 
    MAX(unit.value) AS 'max', 
    isUnique(unit.status) AS 'status' 
FROM unit JOIN `group` ON unit.`group` = `group`.id 
GROUP BY `group`.id 
ORDER BY `group`.id 

應該返回:

--+-------+---+---+------+ 
id|name |min|max|status| 
--+-------+---+---+------+ 
1 | GROUP1|0 |20 | all 0| 
2 | GROUP2|0 |3 | all 1| 
3 | GROUP3|5 |8 | both | 
        (status is in string just to ilustarate returned values) 
+0

組 –

+0

對不起,我寫道,從我的腦海 – Benedictus

+1

GROUP_CONCAT是聰明,優雅,但CASE給予更多的自由,我不知道女巫的答案是更好的。如何票? :) – Benedictus

回答

2

您可以使用GROUP_CONCAT具有獨特的地位,每組

SELECT 
    DISTINCT `group`.id, 
    `group`.name, 
    MIN(unit.value) AS 'min', 
    MAX(unit.value) AS 'max', 
    GROUP_CONCAT(DISTINCT unit.status) AS 'status' 
FROM unit JOIN `group` ON unit.`group` = `group`.id 
GROUP BY `group`.id 
ORDER BY `group`.id 

結果將是

--+-------+---+---+------+ 
id|name |min|max|status| 
--+-------+---+---+------+ 
1 | GROUP1|0 |20 | 0 | 
2 | GROUP2|0 |3 | 1 | 
3 | GROUP3|5 |8 | 1,0 | 

Fiddle

1

由應訂單之前被別的明智的,它會給錯誤試試這個

SELECT 
DISTINCT `group`.id, 
`group`.name, 
MIN(unit.value) AS 'min', 
MAX(unit.value) AS 'max', 
CASE WHEN MAX(unit.status) = MIN(unit.status) 
    Then unit.status Else 'Both' END AS 'status' 
FROM unit JOIN `group` ON unit.`group` = `group`.id 
GROUP BY `group`.id 
ORDER BY `group`.id 

DEMO HERE