tSQL:联接2个表时出现查询UNION错误



我有两个数据集,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'.

您似乎想要JOIN而不是UNION。然而,对于这个数据集,我会选择一个相关的子查询:

select
p.*,
(
select count(*) 
from orderDetails od 
where od.productID = p.productID and od.quantity = 10
) no_orders
from products p

这种方法的好处是:

  • 它避免了外部聚集

  • 你也会得到没有匹配订单的产品的结果(他们会得到0的计数(

  • 无论如何,每个产品只执行一次子查询,因此与join方法相比没有惩罚;假设orderDetails(productID, quantity)上有一个索引,我预计这将表现得同样好,甚至更好

尝试以下操作。

select
productName,
count(*) as total_orders
from products p
join order o
on p.productId = o.productId
where Quantity = 10
group by
productName
Select p.ProductName , count(o.ProductID) from dbo.Products p
join dbo.Orders o
on p.ProductID = o.ProductID where o.Quantity = '10'
group by o.ProductID, p.ProductName

希望这能有所帮助。

最新更新