SQL - 过滤联合

时间:2017-10-13 15:10:04

标签: sql select 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))
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,我们在union结果中得到两行。

我们想要的是,如果有价格>可以忽略price = 0的结果。同一产品在同一天的0个结果。

任何可以分享修复此技巧的人?

2 个答案:

答案 0 :(得分:1)

我不会称之为“诡计”。只需在UNION的price = 0一侧的WHERE子句中添加一个条件,该子句过滤掉价格> 1的产品。 0

我自己使用NOT EXISTS()函数,但还有其他几种方法可以做到这一点。

答案 1 :(得分: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))