2015-09-16 92 views
0

我的查詢返回結果下面,每當​​我看到COLUMN4值的值爲「YES」時,我需要爲COLUMN1組下的所有記錄設置「YES」值。 對於例子DAVID有2條記錄,其中NO和YES-但是我的目標狀態對於所有行都應該是「YES」,因爲他對至少一條記錄具有值「YES」。如何更新在任何行中找到的具有特定值的列

查詢結果

Column1 Column2 Column3 Column4 
================================= 
Mary  AA  AAA  YES 
Mary  BB  BBB  YES 
David AA  AAA  YES 
David BB  BBB  NO 
Clara AA  AAA  NO 
Clara BB  BBB  NO 

要求的目標國家

Column1  Column2  Column3  Column4 
================================================ 
Mary  AA   AAA   YES 
Mary  BB   BBB   YES 
David  AA   AAA   YES 
David  BB   BBB   **YES** 
Clara  AA   AAA   NO 
Clara  BB   BBB   NO 

回答

1

這是你想要的Select語句,

SELECT mt.Column1,mt.Column2,mt.Column3, 
(CASE WHEN mt2.cc IS NULL THEN 'NO' ELSE 'YES' END) AS Column4 
FROM mytable mt LEFT JOIN 
(SELECT Column1,COUNT(*) AS cc FROM mytable WHERE Column4 = 'YES' GROUP BY Column1) 
AS mt2 ON mt2.Column1 = mt.Column1 

結果:

+-------------+-------------+-------------+-------------+ 
| Column1 | Column2 | Column3 | Column4 | 
+-------------+-------------+-------------+-------------+ 
| Mary  |  AA  |  AAA  |  YES | 
+-------------+-------------+-------------+-------------+ 
| Mary  |  BB  |  BBB  |  YES | 
+-------------+-------------+-------------+-------------+ 
| David  |  AA  |  AAA  |  YES | 
+-------------+-------------+-------------+-------------+ 
| David  |  BB  |  BBB  |  YES | 
+-------------+-------------+-------------+-------------+ 
| Clara  |  AA  |  AAA  |  NO  | 
+-------------+-------------+-------------+-------------+ 
| Clara  |  BB  |  BBB  |  NO  | 
+-------------+-------------+-------------+-------------+ 
2
UPDATE my_table m set m.column4='YES' 
WHERE m.column4='NO' 
AND exists(
select 1 from my_table mm where mm.column1= m.column1 and mm.column4 = 'YES') 
+0

您好弗蘭克,感謝您的快速反應。有沒有一種方法可以實現使用Selects,因爲這將成爲我的選擇聲明,我將發佈到我的數據集成工具源限定符中進行進一步的清理。 – Ragav

1

由於意見:

UPDATE my_table m1 set m.column4='YES' 
WHERE m1.column4='NO' 
AND m1.column1 IN (
select m2.column1 from my_table m2 where mm.column4 = 'YES') 
相關問題