【发布时间】:2020-04-23 08:39:26
【问题描述】:
我有 2 个数据集,Products 和 OrderDetails(Northwind 数据集)
产品数据集
ProductID ProductName SupplierID CategoryID QuantityPerUnit UnitPrice UnitsInStock
1 Chai 1 1 10 boxes x 20 bags 18.00 39
2 Chang 1 1 24 - 12 oz bottles 19.00 17
3 Aniseed 1 2 12 - 550 ml 10.00 13
4 Seasoning 2 2 48 - 6 oz jars 22.00 53
5 Gumbo Mix 2 2 36 boxes 21.35 0
订单详情数据集
ProductID UnitPrice OrderID Quantity Discount
1 18.00 10248 10 0
42 9.80 10248 10 0
72 34.80 10248 5 0
1 18.00 10249 10 0
51 42.40 10249 40 0 and so on
1 18.00 10270 12 0
查询
SELECT ProductName, Count([Order Details].OrderID)
FROM ([Order Details] UNION Products ON [Order Details].OrderID = Products.OrderID)
WHERE [Order Details].Quantity = 10
GROUP BY ProductName
预期输出
Product Name (from Products dataset) How many OrderIDs had this product where quantity = 10
Chai 2
由于有 2 个订单 ID 具有 Chai、10248 和 10249,其中数量 = 10,因此我们只考虑了这些情况。 但我在查询中遇到错误' '
Incorrect syntax near the keyword 'UNION'.
【问题讨论】:
-
我认为您将
union与join混淆了 -
UNION不是另一个JOIN。您在查询之间使用它:SELECT x FROM y UNION SELECT z FROM p
标签: sql tsql join group-by union