2017-02-08 28 views
1

我有一個SQL命令其在欄目組至少1特定值的行:的Postgres獲得由另一列

select location,status,total from my_table 

這回:

location - status - total 
city a - active - 3 
city a - pending - 2 
city a - cancel - 4 
city b - pending - 4 
city b - cancel - 4 
city c - active - 2 
city c - cancel - 6 

我怎麼能只返回與城市行至少有一次狀態激活且總數> = 1?

所以,我想回:

location - status - total 
    city a - active - 3 
    city a - pending - 2 
    city a - cancel - 4 
    city c - active - 2 
    city c - cancel - 6 

正如你看到我不想要回B市的原因現在也沒有狀態活躍至少一次與總> = 1

+0

'其中位置(從MY_TABLE選擇的位置在那裏?)' – jarlh

+0

WHERE使用子查詢可以處理存在,或在 –

+0

你的問題回答了它 – GurV

回答

0
select location,status,total from my_table 
where location in (
    select location from my_table 
    where status = 'active' 
     and total >= 1 
    ) 
+0

該查詢忽略其餘行,並只返回具有活動狀態的行..我想返回至少有一次狀態爲活動的城市,但我想要返回所有這些城市..ex:city a - active - 3 ,城市a - 待定 - 2,城市a - 取消 - 4.城市b沒有地位活躍,所以我不想要那個位置..所以,我不需要任何行與城市b ..但城市AI需要3行而不是1 .. – CodeL

+0

此查詢將完全按照您的需要進行,請繼續嘗試。 它是查詢中的子查詢。內部(子)查詢將找到至少有一行同時具有active和total-1的城市。在你的情況下,這將是城市A和C,然後將它們傳遞給父查詢,並將過濾包含城市A和C在內的所有行,包括狀態未激活/總數爲1的行。 –