合并两个查询。

huangapple go评论58阅读模式
英文:

Combine 2 queries together

问题

Query 1:

选择 月份(date),count(id) 作为 total_sold_products
从 产品
在日期在 '2022-01-01' 和 '2022-12-31' 之间

Query 2:

选择 月份(date),count(id) 作为 drinks_sold_products
从 产品
其中 类型 = '饮料' 和 日期在 '2022-01-01' 和 '2022-12-31' 之间

英文:

I am struggling to work out combining a query that should give me 3 columns of Month, total_sold_products and drinks_sold_products

Query 1:

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

Query 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'

I tried the union function but it summed count(id) twice and gave me only 2 columns

Many thanks!

答案1

得分: 0

Union 用于将数据集叠加在一起。您需要条件聚合或联接。请参见下面。

SELECT MONTH(date), 
    COUNT(*) AS total_sold_products,
    COUNT(CASE WHEN type = 'drinks' THEN 1 ELSE 0 END) AS drinks_sold_products, 
    FORMAT((CASE 
         WHEN COUNT(*) > 0 THEN 
            COUNT(CASE WHEN type = 'drinks' THEN 1 ELSE 0 END)/COUNT(*) 
             ELSE 0 END),
    'P') AS 百分比
FROM 产品 
WHERE date BETWEEN '2022-01-01' AND '2022-12-31'
GROUP BY MONTH(date)
英文:

Union is for attaching sets of data on top of each other. You need conditional aggregation or a join. See below.

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

huangapple
  • 本文由 发表于 2023年2月8日 21:02:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定