2014-03-27 68 views
-1

我有這個表:與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 | 

我試圖做一個選擇,我在那裏得到的,例如與線ID = 181和時間戳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 

但此查詢給我的錯誤:被用作表達式的子查詢返回多行 不知道是否有辦法將這些行作爲列返回。

任何想法或建議?

+0

聽起來像你想有一個數據透視表,這是不是很容易在MySQL中:http://buysql.com/mysql/14-how-to-automate-pivot-tables.html –

+0

@MichaelDunlap:謝謝!你有我的方向,因爲我使用的是postgres,我會尋找類似crosstab或crosstab_hash的東西。 –

回答

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` 
+0

我有40個類型,所以我將不得不做40個計數? –

+0

我認爲理論上你可以使用MySQL的動態SQL版本爲數據透視表建立一個查詢。檢查上面Michael的評論中的鏈接。但是,真的,我會嘗試在我的表示層處理樞軸。 – Andrew

+0

我會嘗試使用Michael的想法,但我使用的是postgres。我發現了諸如crosstab或crosstab_hash之類的東西。 –