背景
1、在sql语句中统计一个字段的不同状态时,需要将每个状态的数量查出来,在进行统一输出,涉及表多次查询,下面用一个聚合函数的方式进行查询,比较方便,容易理解。
2、有时候数据表中的时间字段存储的是时间戳格式,如果我们需要按照年月等输出数据时,例如按月统计报表,就需要我们先进行转化和截取,在进行分组,下面语句中通过to_char直接解决,简单方便。
3、以下测试语句为pgsql
测试代码
--在谈项目按月类型统计
SELECT date_month, SUM
( CASE WHEN talk.projecttypename = '融资租赁项目' THEN 1 ELSE 0 END ) zlconut,
SUM ( CASE WHEN talk.projecttypename = '工程建设项目' THEN 1 ELSE 0 END ) jscount
FROM
(
SELECT
projecttypename,
to_char( to_timestamp( createtime / 1000 ), 'yyyy' ) date_year,
to_char( to_timestamp( createtime / 1000 ), 'MM' ) date_month
FROM
dfc_projecttalk
) talk group by date_month
--落户项目按月统计
SELECT date_month, SUM
( CASE WHEN settle.projecttypename = '融资租赁项目' THEN 1 ELSE 0 END ) zlconut,
SUM ( CASE WHEN settle.projecttypename = '工程建设项目' THEN 1 ELSE 0 END ) jscount
FROM
(
SELECT
projecttypename,
to_char( to_timestamp( createtime / 1000 ), 'yyyy' ) date_year,
to_char( to_timestamp( createtime / 1000 ), 'MM' ) date_month
FROM
dfc_projectsettle
) settle group by date_month
--认定项目
SELECT
date_month,
SUM ( CASE WHEN identityp.endscalename = '微型项目' THEN 1 ELSE 0 END ) wxconut,
SUM ( CASE WHEN identityp.endscalename = '一般项目' THEN 1 ELSE 0 END ) ybcount,
SUM ( CASE WHEN identityp.endscalename = '一般大项目' THEN 1 ELSE 0 END ) ybdcount,
SUM ( CASE WHEN identityp.endscalename = '重大项目' THEN 1 ELSE 0 END ) zdcount
FROM
(
SELECT
endscalename,
to_char( to_timestamp( endtime / 1000 ), 'yyyy' ) date_year,
to_char( to_timestamp( endtime / 1000 ), 'MM' ) date_month
FROM
dfc_projectidentify
) identityp
GROUP BY
date_month