【问题标题】:Combine 2 queries together将 2 个查询组合在一起
【发布时间】:2023-02-08 21:08:55
【问题描述】:

我正在努力组合一个查询,该查询应该给我 3 列月份、total_sold_products 和 drinks_sold_products

查询 1:

Select month(date), count(id) as total_sold_products 
from Products 
where date between '2022-01-01' and '2022-12-31'

查询 2

Select month(date), count(id) as drinks_sold_products 
from Products where type = 'drinks' and date between '2022-01-01' and '2022-12-31'

我尝试了 union 函数,但它对 count(id) 求和两次,只给了我 2 列

非常感谢!

【问题讨论】:

  • 仅使用一个查询和条件计数(例如使用 CASE)
  • 请标记您的 DBMS

标签: sql


【解决方案1】:

联合用于攻击彼此之上的数据集。您需要条件聚合或连接。见下文。

    SELECT MONTH(date), 
        COUNT(*) AS total_sold_products,
        COUNT(CASE WHEN type = 'drinks' THEN 1 ELSE 0 END) AS drinks_sold_products
    FROM Products 
    WHERE date BETWEEN'2022-01-01' AND '2022-12-31'
    GROUP BY MONTH(date)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多