我正在获取两个选择查询的UNION,其中一个正在查询的表是一个临时表,以确保输出记录(因此临时表具有每个日期的预期输出,但默认值为0表示销售栏目
示例输出结果将是这样的:
T get_bytes(T const* t) { return getBytes(*t); }
Union根据行删除重复项,如何根据productID和transactionDate列删除重复项,删除Sale为0的重复项?
- 查询以下
ProductID | Product Desc | TransactionDate | Sale
1011021 | SD DOG | 2017-01-07 | 0
1011021 | SD DOG | 2017-01-07 | $17
1011021 | SD DOG | 2017-01-14 | 0
1011021 | SD DOG | 2017-01-14 | $15
1011021 | SD DOG | 2017-01-21 | $21
1011021 | SD DOG | 2017-01-28 | 0
1011021 | SD DOG | 2017-01-28 | $21
答案 0 :(得分:1)
使用not exists
从临时表中选择尚未包含在结果集中的行:
. . .
UNION ALL
SELECT tt.*
FROM temptable tt
WHERE NOT EXISTS (SELECT 1
FROM transactionproducts tp JOIN
transaction t
ON t.transactionID = tp.transactionID
WHERE tp.productId = tt.productId AND
t.transactionDate = tt.transactionDate
)
GROUP BY productID, productDesc, Sale, transactionDate
ORDER BY transactionDate
答案 1 :(得分:0)
这个怎么样:
SELECT transactionProducts.productID, products.productDesc, sum(salePrice) as Sale, transactionDate
FROM products LEFT JOIN transactionProducts on products.productID = transactionProducts.productID
LEFT JOIN transactions ON transactionProducts.transactionID = transactions.transactionID
LEFT JOIN productCategory on productCategory.productID = products.productID
LEFT JOIN categories on categories.categoryID = productCategory.categoryID
WHERE (transactionProducts.productID='123' AND transactions.transactionDate='2017-01-12'
AND sum(salePrice) > 0 )
Group by transactionProducts.productID, transactionDate
UNION select * from "temptable" group by productID, productDesc, Sale, transactionDate
ORDER BY transactionDate
注意,我已将“AND sum(salePrice)> 0”添加到第一个SELECT WHERE子句中。
HTH