从同一个表中使用COUNT进行SELECT

时间:2014-03-27 20:50:16

标签: sql postgresql select count

我有这张桌子:

id   |                timestamp            |     type    |    
-----+-------------------------------------+-------------+
 175 | 2013-02-28 00:00                    |         1   |
 176 | 2013-02-28 00:00                    |         1   |
 177 | 2013-02-28 00:00                    |         2   |
 178 | 2013-02-28 00:00                    |         2   |
 179 | 2013-02-28 00:00                    |         1   |
 180 | 2013-02-28 00:00                    |         1   |
 181 | 2013-03-01 00:00                    |         10  |
 182 | 2013-03-01 00:00                    |         2   |
 183 | 2013-03-01 00:00                    |         2   |
 184 | 2013-03-01 00:00                    |         1   |

我正在尝试进行SELECT,我得到的地方,例如id = 181和timestamp 2013-03-01 00:00的行,并返回一周之前每种类型的类型计数。我正在尝试返回类似的东西:

 id  |                timestamp            |     type    | type1 | type2 | type3 |
-----+-------------------------------------+-------------+-------+-------+-------+
 181 | 2013-03-01 00:00                    |         10  |   4   |   2   |   0   |

我做了这个查询:

SELECT timestamp, type, 
(SELECT COUNT(CASE WHEN type = 1 THEN 1 END) AS types FROM i
    WHERE timestamp BETWEEN (SELECT date_trunc('week', timestamp) - interval '7 days') AND ((SELECT date_trunc('week', timestamp) - interval '7 days') + interval '7 days')
    GROUP BY timestamp, type)
FROM i 
WHERE timestamp BETWEEN '2013-03-01' AND '2013-03-01' AND i.tipo = '4'
GROUP BY timestamp, type

但是这个查询给了我错误:用作表达式的子查询返回了多行 Dunno如果有办法将这些行作为列返回。

有任何想法或建议吗?

1 个答案:

答案 0 :(得分:0)

为了得到你的开始日期,我只使用了一个子查询。 如果您有一组相对较小的类型值,则可以使用CASE语句计算每种类型:

count(case when `type` = 1 then t1.`id` else null end) as Type1

SQL Fiddle

select
t2.`id`,
count(case when `type` = 1 then t1.`id` else null end) as Type1,
count(case when `type` = 2 then t1.`id` else null end) as Type2
from
i t1,
(select
 `id`,
`timestamp` as ts
from
i
where
`id` = 181 ) t2
where
timestamp
between date_add(t2.ts, interval -7 day) and t2.ts
and t1.id < 181
group by
t2.`id`