PSQL - 在左连接后不返回空列

时间:2017-09-18 23:11:41

标签: ruby-on-rails postgresql

我想做一个聚合,计算按小时分组的总销售额。我需要在过去24小时内退回所有小时,无论他们是否有销售,并包括在该小时内发生的销售。

要做到这一点,我这样做SELECT * FROM GENERATE_SERIES( date_trunc('hour', current_timestamp - interval '23 hour'), date_trunc('hour', current_timestamp), '1 hour' ) ......

generate_series
------------------------
 2017-09-17 16:00:00-07
 2017-09-17 17:00:00-07
 2017-09-17 18:00:00-07
 2017-09-17 19:00:00-07
 2017-09-17 20:00:00-07
 2017-09-17 21:00:00-07
 2017-09-17 22:00:00-07
 2017-09-17 23:00:00-07
 2017-09-18 00:00:00-07
 2017-09-18 01:00:00-07
 2017-09-18 02:00:00-07
 2017-09-18 03:00:00-07
 2017-09-18 04:00:00-07
 2017-09-18 05:00:00-07
 2017-09-18 06:00:00-07
 2017-09-18 07:00:00-07
 2017-09-18 08:00:00-07
 2017-09-18 09:00:00-07
 2017-09-18 10:00:00-07
 2017-09-18 11:00:00-07
 2017-09-18 12:00:00-07
 2017-09-18 13:00:00-07
 2017-09-18 14:00:00-07
 2017-09-18 15:00:00-07
(24 rows)

返回以下行

SELECT
  date_trunc('hour', orders.ordered_at) as hour,
  COALESCE(SUM(orders.total), 0) AS price,
  #{merchant.id} AS merchant_id
FROM GENERATE_SERIES(
  date_trunc('hour', current_timestamp - interval '23 hour'),
  date_trunc('hour', current_timestamp),
  '1 hour'
) AS h
LEFT JOIN orders
  ON date_trunc('hour', orders.ordered_at) = h
  AND orders.merchant_id = merchant_id
GROUP BY hour
ORDER BY hour DESC;

到目前为止这是好事。现在我想加入我的订单表来获取数字。我这样做......

hour         |  price  | merchant_id
---------------------+---------+-------------
                     |       0 |           1
 2017-09-18 09:00:00 | 2934.00 |           1
(2 rows)

当我跑步时,我得到了这个......

Dim checkedCount = DataGridView1.Rows.
                                 Cast(Of DataGridViewRow)().
                                 Where(Function(row) Not row.IsNewRow).
                                 Count(Function(row) CBool(row.Cells(0).Value))

Select Case checkedCount
    Case 0
        'No rows are checked.
    Case 1
        'One row is checked.
    Case Else
        'More than one row is checked.
End Select

2个问题......

1 - 为什么我有一个NULL小时

2 - 我所有其他时间都去了哪里?我期待24行,其中一行有价格,其他行有0价格

1 个答案:

答案 0 :(得分:1)

你的NULL小时是因为你从错误的桌子上拉它。相反,使用:

SELECT gs.hh, COALESCE(SUM(o.total), 0) AS price,
       #{merchant.id} AS merchant_id
FROM GENERATE_SERIES(date_trunc('hour', current_timestamp - interval '23 hour'),
                     date_trunc('hour', current_timestamp),
                     '1 hour'
                    ) gs(hh) LEFT JOIN
      orders o
      ON date_trunc('hour', o.ordered_at) = gs.hh AND
         o.merchant_id = merchant_id
GROUP BY gs.hh
ORDER BY gs.hh DESC;

我猜你也希望你的ON条款是:

ON o.merchant_id = #{merchant.id} 

因为o.merchant_id = merchant_id应该被解释为o.merchant_id = o.merchant_id