作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这里我想以下面的形式打印数据。
示例:
callnumber1|callnumber2|CALL-IN|CALL-OUT|SMS-IN|SMS-OUT|FirstCallDate|LastCallDate
--------- +-------------+---------+----------+--------+---------+---------------+----
123456 | 654321 | 1 | 2 | 1 | 1 | 2014-02-12 | 2013-03-12
23456 | 54321 | 0 | 1 | 0 | 1 | 2014-02-12 | 2013-03-12
表:表1
create table table1
(
callnumber1 int,
callnumber2 int,
calltype varchar,
calldate date
);
插入一些数据
insert into table1 values(123456,654321,'CALL-IN','1-2-2014');
交叉表查询。
select * from crosstab($$select callnumber1,callnumber2,calltype,calldate,count(callnumber1||callnumber2) as totalcalls
from table1
where calltype in ('CALL-IN','CALL-OUT','SMS-IN','SMS-OUT')
group by callnumber1,callnumber2,calltype
order by callnumber1,callnumber2,calltype
$$,
$$ values('CALL-IN'),('CALL-OUT'),('SMS-IN'),('SMS-OUT')$$)
as table1(callnumber1 int,callnumber2 int,"CALL-IN" int,"CALL-OUT" int,"SMS-IN" int,"SMS-OUT" int,FirstCallDate date,LastCallDate date);
最佳答案
为此您不需要 crosstab()
。条件计数可以完成这项工作:
SELECT callnumber1, callnumber2
, count(calltype = 'CALL-IN' OR NULL) AS call_in
, count(calltype = 'CALL-OUT' OR NULL) AS call_out
, count(calltype = 'SMS-IN' OR NULL) AS sms_in
, count(calltype = 'SMS-OUT' OR NULL) AS sms_out
, min(calldate) AS first_calldate
, max(calldate) AS last_calldate
, count(*) AS total_calls
FROM table1
WHERE calltype in ('CALL-IN','CALL-OUT','SMS-IN','SMS-OUT')
GROUP BY 1,2
ORDER BY 1,2
使用 count(*)
而不是 count(callnumber1||callnumber2)
,假设两列都定义为 NOT NULL。
count(calltype = 'CALL-IN' OR NULL)
是如何工作的?
Compute percents from SUM() in the same SELECT sql query
关于sql - Postgresql:如何在 PostgreSQL 中使用 "crosstab"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22222032/
我是一名优秀的程序员,十分优秀!