【问题标题】:sql check for no result in group by clausesql检查group by子句中没有结果
【发布时间】:2016-06-10 23:42:25
【问题描述】:

我有一个 mysql

的 sql 查询
select sum(quantity), Hour(posted)
from orders
where posted between '05-10-2014' and '05-10-2014' // my timestamp here
group by Hour(posted)

结果可能是

sum, hour
10, 0
12, 1
13, 3 // note 2 missing in hours
13, 5 // note hour 4 is missing

我需要的是

sum,hour
10,0
12,1
0, 2 // 0 for missing hour ( where no record was found in that hour)
13,3 
0, 4 // 0 for missing hour ( where no record was found in that hour)
13,5 

我该怎么做?任何帮助表示赞赏

【问题讨论】:

  • 用 1 到 24 的数字(或者你想要的)创建一个表格,然后 LEFT JOIN 将它添加到你的表格中。
  • 在我有一个大数据集的情况下,再添加一个 LEFT JOIN 对我来说似乎不合理,特别是当它除了 1 到 24 之外什么都不包含时.. 可能是我想错了..但这就是我现在的想法..
  • @PM77-1,你说得非常对兄弟......第二个链接是我正在寻找的答案......你能把它作为答案发布吗?
  • posted between '' and '' 没有任何意义。你想用它做什么?另外:您使用的是哪个 DBMS?

标签: sql select group-by


【解决方案1】:

如果您使用的是 SqlServer,您可以使用以下 TSQL 查询来获得所需的结果:

with [hours] as 
( SELECT DISTINCT hour = number 
FROM master..[spt_values] 
WHERE number BETWEEN 1 AND 24
)

select ISNULL(sum(orders.quantity),0) as quantity, [hours].[hour]
from hours left join orders  on hours.hour =   datepart(hour,posted)
group by [hours].[hour]

【讨论】:

    【解决方案2】:

    Group by all 保留在 where 子句中过滤的值为 0 的组:

    select sum(quantity), Hour(posted)
    from orders
    where posted between '' and ''
    group by all Hour(posted)
    

    【讨论】:

    • 这不会在结果中为您提供缺失的小时数!
    【解决方案3】:

    无需创建仅包含 1、2、3 的物理表...使用 CTE 创建它。

    with hours as (
    select 0 hour
    union all
    select hour+1 from hours
    where hour < 23
    )
    select hour, isnull(sum(quantity), 0) qty 
    from hours h 
    left join orders o on h.hour = o.Hour(posted)
    where  posted between '05-10-2014' and '05-10-2014' --your range
    group by h.hour
    

    【讨论】:

    • 不确定这是否会在 laravel DB Query builder 中转换,对我来说似乎真的很难......但是,我会这样做......
    猜你喜欢
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2015-12-18
    相关资源
    最近更新 更多