2017-10-13 124 views
1

有這樣一個聯盟:SQL - 過濾工會的結果

(SELECT prod.id, price, timestamp 
FROM products prod JOIN prices price ON prod.id = price.productid 
WHERE price > 0 
GROUP BY prod.id, DATE(timestamp)) 
UNION 
(SELECT prod.id, price, timestamp 
FROM products prod JOIN prices price ON prod.id = price.productid 
WHERE price = 0 
GROUP BY prod.id, DATE(timestamp)) 

問題:

如果有日期,其中一個產品是可用的價格= 0和價格> 0,我們在聯合結果中獲得兩行。

我們想要的是,如果同一日期的同一產品的價格> 0,那麼價格= 0的結果將被忽略。

任何人都可以分享伎倆來解決這個問題嗎?

回答

1

我不會稱之爲「詭計」。只需在UNION的price = 0側的WHERE子句中添加一個條件,即可篩選出價格大於0的產品。

我會用NOT EXISTS()函數自己做,但還有其他幾種如何做到這一點。

0

您是否試圖將「有價格」與「僅有0價格」分開分組? 如果是這樣,則將第一個組放入臨時表中,爲產品ID不在臨時表中的第二個組執行選擇。

CREATE TABLE #HASPRICE (prod.id INT, price Decimal, timestamp DATE) 

INSERT INTO #HASPRICE 
SELECT prod.id, price, timestamp 
FROM products prod JOIN prices price ON prod.id = price.productid 
WHERE price > 0 
GROUP BY prod.id, DATE(timestamp) 

INSERT INTO #HASPRICE 
SELECT prod.id, price, timestamp 
FROM products prod JOIN prices price ON prod.id = price.productid 
WHERE price = 0 AND prod.id not in (select prod.id from #HASPRICE) 
GROUP BY prod.id, DATE(timestamp)) 

如果沒有,那麼這將工作

(SELECT prod.id, price, timestamp 
FROM products prod JOIN prices price ON prod.id = price.productid 
WHERE price >= 0 
GROUP BY prod.id, DATE(timestamp))