从Postgresql中的时间范围计数

时间:2017-06-09 09:29:13

标签: postgresql

我有一个查询,计算每天每小时在我们的服务中注册的用户总数。我的问题是我希望在范围风格中出现小时。您可以在下面看到:

查询:

    SELECT
    case
      when extract(dow from us.created::timestamp) = 0 then 'Sunday'
      when extract(dow from us.created::timestamp) = 1 then 'Monday'
      when extract(dow from us.created::timestamp) = 2 then 'Tuesday'
      when extract(dow from us.created::timestamp) = 3 then 'Wednesday'
      when extract(dow from us.created::timestamp) = 4 then 'Thursday'
      when extract(dow from us.created::timestamp) = 5 then 'Friday'
      when extract(dow from us.created::timestamp) = 6 then 'Saturday'
      end as wday,
    extract(hour from us.created::timestamp)  as whour,
    count(us.id)
  FROM users us
  GROUP BY wday,whour order by wday, whour

查询结果:

wday whour count
Friday 0 364
Friday 1 156
Friday 2 79
Friday 3 39
Friday 4 55
Friday 5 32 ....

我想计算并以这种格式显示结果:

wday whour count
Friday 0-1 364
Friday 1-2 156
Friday 2-3 79
Friday 3-4 39
Friday 4-5 55
Friday 5-6 32 ....

我该怎么做?

1 个答案:

答案 0 :(得分:0)

尝试像:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Dequeue your cell
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "YourCustomCellIdentifier") as! YourCustomTableViewCell

        // get picture url from the data array
        let pictureUrl = self.yourCellsData[indexPath.row].pictureUrl

        // async download
        cell.pictureView.af_setImage(
                withURL:  URL(string: pictureUrl)!,
                placeholderImage: UIImage(named: "YourPlaceholder.png"),
                filter: nil,
                imageTransition: UIImageView.ImageTransition.crossDissolve(0.5),
                runImageTransitionIfCached: false) {
                    // Completion closure
                    response in
                        if response.response != nil {
                            // Force the cell update
                            self.tableView.beginUpdates()
                            self.tableView.endUpdates()
                        }
                }

        return cell
        }

这是逻辑样本:

WITH a as (
   SELECT 
    to_char(us.created::timestamp,'Day') as wday,
    extract(hour from us.created::timestamp)  as whour,
    count(us.id)
  FROM users us
  GROUP BY wday,whour
)
select 
  wday
, coalesce(whour,'-',lead(whour) over (partition by wday order by whour)) whour
, count
from a
 order by wday, whour