0

I have a table like this:

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

And I am trying to a result like this:

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

Where the numbers represent the counts of the rows of respective type in the given date range.

I have tried things along these lines:

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

But that returned the same number (total count in given date range) for each type. When I added the GROUP BY statement to the sub-selects, I got an error saying that a subselect returned more than one row.

So how do I solve this?

Thank you very much in advance!

4

1 回答 1

1

You want conditional aggregation:

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;

That is, put your logic into the sum() -- your question suggests that you understand that logic.

于 2013-08-29T20:45:19.647 回答