Postgres Count函数用于月度交易,仅计算明显

时间:2015-10-13 04:38:44

标签: postgresql

我在计算部门内团队的规模。所有员工的员工ID均以" E"然后是一个指定号码(即" 0"," 1"等)来表示他们所在的队伍。

我在Postgres中有以下查询来计算团队的大小,但问题是,对于这个查询,我得到了很多空行,因为有些月份是重复的。例如,包含" May / 2016"的行可能会重复3次,只有1行包含实际的团队计数。

select to_char("Date", 'Mon/YYYY') as "Date",
 sum(case when l_part LIKE 'E0%%' then count end) as "ACCOUNTING",
 sum(case when l_part LIKE 'E1%%' then count end) as "SW",
 sum(case when l_part LIKE 'E2%%' then count end) as "SUPPORT",
 sum(case when l_part LIKE 'E3%%' then count end) as "CALLCENTER",
 sum(case when l_part LIKE 'E4%%' then count end) as "ADMIN",
 sum(case when l_part LIKE 'E5%%' then count end) as "MARKETING",
 sum(case when l_part LIKE 'E9%%' then count end) as "MANAGEMENT"
from (
 select left("Type",4)as l_part, count(*),"Date" from 
  "Transactions" group by "Date",l_part
 ) p group by "Date"

 order by min("Date");

如果我能将每个月的计数减少到一行/ yyyy,并按照有用且不那么混乱的日期排序。对我尝试的任何调整表示赞赏。

这是填充的内容,作为使用2015年9月的示例:

这就是我得到的:

DATE  |   ACCOUNTING |  SW | SUPPORT | CALLCENTER | ADMIN  | MARKETING  |
Sep/15|              |     |         |            |        |            |
Sep/15|              |     |         |            |        |            |
Sep/15|      1       |  2  |    1    |     5      |   5    |    3       |

1 个答案:

答案 0 :(得分:1)

我怀疑你的问题是GROUP BY子句,我认为这是用DATE_TRUNC()解决的。不确定你是否需要where子句。

SELECT
      to_char(DATE_TRUNC('month',"Date"), 'Mon/YYYY') as "Date"
    , SUM(CASE WHEN left("Type",4) LIKE 'E0%%' THEN 1 END) AS "ACCOUNTING"
    , SUM(CASE WHEN left("Type",4) LIKE 'E1%%' THEN 1 END) AS "SW"
    , SUM(CASE WHEN left("Type",4) LIKE 'E2%%' THEN 1 END) AS "SUPPORT"
    , SUM(CASE WHEN left("Type",4) LIKE 'E3%%' THEN 1 END) AS "CALLCENTER"
    , SUM(CASE WHEN left("Type",4) LIKE 'E4%%' THEN 1 END) AS "ADMIN"
    , SUM(CASE WHEN left("Type",4) LIKE 'E5%%' THEN 1 END) AS "MARKETING"
    , SUM(CASE WHEN left("Type",4) LIKE 'E9%%' THEN 1 END) AS "MANAGEMENT"
FROM "Transactions"
WHERE "Date" IS NOT NULL
GROUP BY
      DATE_TRUNC('month',"Date")
ORDER BY
      DATE_TRUNC('month',"Date")
  

顺便说一句:使用COUNT()的替代方案不是SUM(),而是:

SELECT
      to_char(DATE_TRUNC('month',"Date"), 'Mon/YYYY') as "Date"
    , COUNT(CASE WHEN left("Type",4) LIKE 'E0%%' THEN 1 END) AS "ACCOUNTING"
    , COUNT(CASE WHEN left("Type",4) LIKE 'E1%%' THEN 1 END) AS "SW"
    , COUNT(CASE WHEN left("Type",4) LIKE 'E2%%' THEN 1 END) AS "SUPPORT"
    , COUNT(CASE WHEN left("Type",4) LIKE 'E3%%' THEN 1 END) AS "CALLCENTER"
    , COUNT(CASE WHEN left("Type",4) LIKE 'E4%%' THEN 1 END) AS "ADMIN"
    , COUNT(CASE WHEN left("Type",4) LIKE 'E5%%' THEN 1 END) AS "MARKETING"
    , COUNT(CASE WHEN left("Type",4) LIKE 'E9%%' THEN 1 END) AS "MANAGEMENT"

对于遇到的任何NON-NULL值,COUNT()递增1。