【问题标题】:Returns new columns for selected values返回选定值的新列
【发布时间】:2021-04-25 18:52:18
【问题描述】:

如何编写一个查询来修复 Guava 和 Berry 的数量与 no_of_fruits 的数量相同? Guava 和 Berry 有自己的编号。

PS。 fruits_opt 列有两个值(Guava 和 Berry)

SELECT 
DATETRUNC(date_ts,'dd') AS day,
COUNT(sold_fruits) AS no_of_fruits_sold,
COUNT( fruits_opt =  'Guava')AS Guava, 
COUNT( fruits_opt =  'Berry')AS Berry 
FROM beginner_1
GROUP BY DATETRUNC(date_ts,'dd')
ORDER BY DATETRUNC(date_ts,'dd');

当前结果:

day no_of_fruits_sold Guava Berry
2021-01-06 00:00:00 120 120 120
2021-01-07 00:00:00 50 50 50
2021-01-08 00:00:00 100 100 100
2021-01-09 00:00:00 80 80 80

想要的结果:

day no_of_fruits_sold Guava Berry
2021-01-06 00:00:00 120 80 40
2021-01-07 00:00:00 50 19 31
2021-01-08 00:00:00 100 67 33
2021-01-09 00:00:00 80 52 28

【问题讨论】:

  • 您确定您使用的是 Postgres 吗?没有datetrunc() 功能 - 只有date_trunc()
  • 我没有使用 Postgres,但它的语法最接近。
  • 那我的回答现在很可能没用了

标签: sql aggregation


【解决方案1】:

COUNT(fruits_opt = 'Guava') 没有做你认为的事情。

fruits_opt = 'Guava' 返回truefalse 但从不返回null,因此所有行都被计算在内。而count<expression>) 计算<expression> 不为空的所有行

使用过滤聚合:

count(*) filter (where fruits_opt = 'Guava')

【讨论】:

    【解决方案2】:

    您不能在布尔表达式上使用 count()。当您的条件为真时,用例计数 1。如果条件为假,则返回 null。下面的查询应该符合您的目的:

    SELECT 
    DATETRUNC(date_ts,'dd') AS day,
    COUNT(sold_fruits) AS no_of_fruits_sold,
    COUNT( case when fruits_opt =  'Guava' then 1 end)AS Guava, 
    COUNT( case when fruits_opt =  'Berry' then 1 end)AS Berry 
    FROM beginner_1
    GROUP BY DATETRUNC(date_ts,'dd')
    ORDER BY DATETRUNC(date_ts,'dd');
    

    【讨论】:

      【解决方案3】:

      你还没有说你使用的是什么数据库,所以这里有一个选项纲要。

      标准 SQL,但在许多数据库中不受支持:

      COUNT(*) FILTER (WHERE fruits_opt =  'Guava') AS Guava, 
      

      标准 SQL,随处支持,但冗长:

      SUM(CASE WHEN fruits_opt =  'Guava' THEN 1 ELSE 0 END) as Guava
      

      标准 SQL,随处支持,但冗长,我发现代码有点误导,因为当 1 替换为 02 而不是 NULL 时,它返回相同的值:

      COUNT(CASE WHEN fruits_opt =  'Guava' THEN 1 END) as Guava
      

      非标准,依赖隐式转换为int:

      SUM( fruits_opt =  'Guava' ) as Guava
      

      非标准,使用 Postgres 简写进行显式转换(许多 Postgres 派生数据库都支持 ::):

      SUM( (fruits_opt =  'Guava')::INT ) as Guava
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多