2017-07-06 112 views
0

假設我有一個表在蜂巢像這樣至少有一行:蜂巢 - 從選擇組數據包含

|Id|Data |Data2 |Groupkey| 
|1 |One |  |Group1 | 
|2 |Two |Stuff |Group1 | 
|3 |Shoes|Some |Group2 | 
|4 |four |Stuff |Group2 | 
|5 |Three|Notme |Group3 | 

對於包含「東西」在Data2我想有該行各組來自'Stuff'行的StuffData2以外的行中的GroupkeyData

所以得出的數據集看起來像

|Group |Data |Data2| 
|Group1|One |Two | 
|Group2|Shoes|four | 

我希望得到的東西與GROUP BY去,我開始與

SELECT Data, Groupkey FROM (SELECT Data, GroupKey FROM MyTable GROUP BY Groupkey) WHERE Data2 <> 'Stuff'去,但這個失敗提示我需要包括在數據分組,但那不是我想要分組的?

而我不知道如何選擇只包含一行與特定數據的組。

回答

0
select  Groupkey           as `Group` 
      ,min (case when Data2 <> 'Stuff' then Data end)  as Data 
      ,min (case when Data2 = 'Stuff' then Data end)  as Data2 

from  MyTable 

group by Groupkey 

having  count (case when Data2 = 'Stuff' then 1 end) > 0 
; 

+--------+-------+-------+ 
| group | data | data2 | 
+--------+-------+-------+ 
| Group1 | One | Two | 
| Group2 | Shoes | four | 
+--------+-------+-------+ 
0
SELECT DISTINCT Groupkey, t1.Data, t2.Data as Data2 
FROM t t1 
INNER JOIN t t2 
ON t1.Groupkey = t2.Groupkey 
AND t1.Data2 <> t2.Data2 
WHERE t2.Data2 = 'Stuff'