2016-12-07 52 views
1


大家好, 我有这样的访客表:计数每月访问者人数

ID | Date | Purpose 
1 | 20/10/2016 | Purpose1 
2 | 22/10/2016 | Purpose1 
3 | 25/10/2016 | Purpose2 
4 | 12/11/2016 | Purpose1 
5 | 14/11/2016 | Purpose2 
6 | 16/11/2016 | Purpose2 

目前我使用此查询:

select case 
      when date like '%/10/2016' then '10/2016' 
      when date like '%/11/2016' then '11/2016' 
     end as month, count(*) as total 
     from visitors 
     where 
      date like '%/10/2016' 
      or date like '%/11/2016' 
     GROUP by month 

我只能拿个月,上面查询的总列数。我怎样才能达到这个结果?

Month | Total | Purpose1 | Purpose2 
10/2016 | 3 | 2 | 1 
11/2016 | 3 | 1 | 2 

谢谢!

+0

提示:商店使用日期日期数据类型 – Strawberry

回答

0

考虑以下...

DROP TABLE IF EXISTS my_table; 

CREATE TABLE my_table 
(ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY 
,Date DATE NOT NULL 
,Purpose VARCHAR(12) NOT NULL 
); 

INSERT INTO my_table VALUES 
(1,'2016-10-20','Purpose1'), 
(2,'2016-10-22','Purpose1'), 
(3,'2016-10-25','Purpose2'), 
(4,'2016-11-12','Purpose1'), 
(5,'2016-11-14','Purpose2'), 
(6,'2016-11-16','Purpose2'); 

SELECT DATE_FORMAT(date,'%Y-%m') month 
    , SUM(purpose = 'purpose1') purpose1 
    , SUM(purpose = 'purpose2') purpose2 
    , COUNT(*) total 
    FROM my_table 
GROUP 
    BY month; 
+---------+----------+----------+-------+ 
| month | purpose1 | purpose2 | total | 
+---------+----------+----------+-------+ 
| 2016-10 |  2 |  1 |  3 | 
| 2016-11 |  1 |  2 |  3 | 
+---------+----------+----------+-------+ 

..或者(在我看来,更好的,只要你有访问应用程序代码)...

SELECT DATE_FORMAT(date,'%Y-%m') month 
    , purpose 
    , COUNT(*) total 
    FROM my_table 
GROUP 
    BY month 
    , purpose; 

+---------+----------+-------+ 
| month | purpose | total | 
+---------+----------+-------+ 
| 2016-10 | Purpose1 |  2 | 
| 2016-10 | Purpose2 |  1 | 
| 2016-11 | Purpose1 |  1 | 
| 2016-11 | Purpose2 |  2 | 
+---------+----------+-------+ 
+0

非常感谢!它现在正在工作。 – ian

0

转置表并不是很快。在一些小程序中这样做最好。

如果你做一个

select case 
      when date like '%/10/2016' then '10/2016' 
      when date like '%/11/2016' then '11/2016' 
     end as month, count(*) as total, Purpose 
     from visitors 
     where 
      date like '%/10/2016' 
      or date like '%/11/2016' 
     GROUP by month, Purpose 

您将有一个很好的起点。 您可能需要添加ORDER BY子句(取决于您的DBMS)。

如果(且仅当)您的表中只有两个目的,且表的大小不是很大,则可以创建两个视图并加入它们。

+0

转置表可能并不快。不能使用索引的查询肯定很慢。 – Strawberry

+0

没有关于这个问题的讨论。但是如果你想转换桌面并碰巧有50个目的,你将需要相当多的连接。这会增加不能使用索引的惩罚因子为50. – Ronald

+0

感谢您的回答,目前我只有三个目的 – ian