【问题标题】:Divide two counts in one selection (with date_trunc)在一个选择中划分两个计数(使用 date_trunc)
【发布时间】:2023-01-28 23:04:44
【问题描述】:

我想在单个查询中划分两个 Counts,但是 DATE_TRUNC 导致了一些问题

到目前为止,我在 postgre 中有一个如下所示的查询:

SELECT DATE_TRUNC('month', "Date") as date, 
COUNT(*) as AllTransactions,
COUNT(*) filter (where "State"='ACCEPTED') as Accepted,
FROM "Acceptance_Report"
GROUP BY 1
ORDER BY 1

它返回这个:

Date AllTransactions Accepted
2019-01-01 930 647
2019-02-01 840 589

现在我需要得到百分比,所以它应该是Accepted/AllTransactions*100

我知道我可以创建另一个表并使用 INSERT ,但我觉得还有另一种简单的方法可以在单个查询中完成。

你有什么想法?

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    所以如果你想分开它们,重复这些表达式。但将其中一个计数转换为数值很重要,否则会导致整数除法(其中 1/5 产生 0

    SELECT DATE_TRUNC('month', "Date") as date, 
           COUNT(*) as AllTransactions,
           COUNT(*) filter (where "State"='ACCEPTED') as Accepted,
           COUNT(*)::numeric  / COUNT(*) filter (where "State"='ACCEPTED') as pct
    FROM "Acceptance_Report"
    GROUP BY 1
    ORDER BY 1
    

    如果不想重复表达式,可以使用派生表:

    select "date", 
           alltransactions, 
           accepted, 
           alltransactions::numeric / accepted as pct
    FROM (
      SELECT DATE_TRUNC('month', "Date") as date, 
             COUNT(*) as AllTransactions,
             COUNT(*) filter (where "State"='ACCEPTED') as Accepted
      FROM "Acceptance_Report"
      GROUP BY 1
      ORDER BY 1
    ) t
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-06
      • 2011-05-02
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多