【问题标题】:SQL: Query UNION Error while joining 2 tablesSQL:连接 2 个表时查询 UNION 错误
【发布时间】: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'.

【问题讨论】:

  • 我认为您将 unionjoin 混淆了
  • UNION 不是另一个JOIN。您在查询之间使用它:SELECT x FROM y UNION SELECT z FROM p

标签: sql tsql join group-by union


【解决方案1】:

您似乎想要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)上的索引,我希望这会表现得同样好,或者更好。

【讨论】:

  • 。 .您可能想要对您回答的有反对票的问题进行投票。他们有一个令人不安的习惯,即在未来的某个时间点被删除。当问题对您来说似乎很清楚并且因为不清楚而被关闭时,这尤其令人恼火。
  • @GordonLinoff:我通常会这样做,但我可能忘记了这个。固定的。总体而言,我发现在 SO 上的问题经常被否决……我发现缺乏赞成票已经很好地表明了问题的质量!
【解决方案2】:

试试下面的。

select
    productName,
    count(*) as total_orders
from products p
join order o
on p.productId = o.productId
where Quantity = 10
group by
    productName

【讨论】:

    【解决方案3】:
    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
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-11-18
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 2014-01-28
      • 2021-06-23
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      相关资源
      最近更新 更多