2013-08-29 72 views
0

我有一個表是這樣的:MySQL的按類型分組,然後在列按日期範圍切片

+----+------+-------------+ 
| id | type | date  | 
+----+------+-------------+ 
| 1 | abc | [some date] | 
| 2 | def | [some date] | 
| 3 | abc | [some date] | 
| 4 | abc | [some date] | 
| 5 | xyz | [some date] | 
+----+------+-------------+ 

而且我想這樣的結果:

+------+-----------+------------+-----------+ 
| type | last year | last month | last week | 
+------+-----------+------------+-----------+ 
| abc |  5489 |  355 |  101 | 
| def |  2235 |  115 |  59 | 
| xyz |  1998 |  180 |  75 | 
+------+-----------+------------+-----------+ 

凡數字代表在給定日期範圍內的各種類型的行的計數。

我已經試過的東西沿着這些路線:

SELECT type, 
    (SELECT count(*) FROM table WHERE [date last year]) AS `last year`, 
    (SELECT count(*) FROM table WHERE [date last month]) AS `last month`, 
    (SELECT count(*) FROM table WHERE [date last week]) AS `last week` 
FROM table 
GROUP BY type 

但返回的相同數量(在指定日期範圍內總數)爲每種類型。當我將GROUP BY語句添加到子選擇時,我收到一個錯誤消息,指出一個子選擇返回多行。

那麼我該如何解決這個問題呢?

非常感謝您提前!

回答

1

你想有條件聚集:

SELECT type, 
     sum([date last year]) AS `last year`, 
     sum([date last year]) AS `last year`, 
     sum([date last month]) AS `last month`, 
     sum([date last week]) AS `last week` 
FROM table 
GROUP BY type; 

也就是說,把你的邏輯到sum() - 你的問題表明,你理解的邏輯。