我使用以下SQL从我们的数据库获取访问次数:
SELECT
t.country, MONTH(visit_date), t.visits
FROM
visits t
WHERE
t.visit_date BETWEEN '2017-01-01' AND '2017-12-31'
ORDER BY
t.country
此查询的结果如下:
Country Month Visits
-------------------------------
DE 1 5.000
DE 2 6.000
: : :
: : :
US 1 5.400
US 2 3.000
: : :
: : :
到目前为止,一切正常。
现在我想对结果进行透视,以便最终看起来像这样:
1 2 3 4
DE 10.000 15.000 30.000 20.000
US 20.220 18.400 40.000 19.000
因此,我尝试使用以下SQL:
SELECT
*
FROM
(SELECT t.country, MONTH(visit_date), t.visits
FROM visits t
WHERE t.visit_date BETWEEN '2017-01-01' AND '2017-12-31'
ORDER BY t.country) AS s
PIVOT
(SUM(t.visits)
FOR MONTH(t.visit_date) IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
) AS pvt
但是,此查询引发错误:
错误代码:1064。您的SQL语法有错误;请查看与您的数据库服务器版本相对应的手册,以获取正确的语法,以在“ PIVOT(SUM(t.unique_visits)FOR MONTH(t.visit_date)IN(1、2、3、4、5、6、7,在第7行
您是否知道我的查询中有错误?
答案 0 :(得分:1)
答案 1 :(得分:0)
MySQL不提供PIVOT
功能。您将必须自行构建数据透视表。一种常用的方法是conditional aggregation
。
您可以像这样更改查询以获得所需的输出。
SELECT
country,
SUM(CASE WHEN month = 1 THEN visits END) AS '1',
SUM(CASE WHEN month = 2 THEN visits END) AS '2',
SUM(CASE WHEN month = 3 THEN visits END) AS '3',
SUM(CASE WHEN month = 4 THEN visits END) AS '4'
FROM
(SELECT
t.country, MONTH(visit_date) month, t.visits
FROM visits t
WHERE t.visit_date BETWEEN '2017-01-01' AND '2017-12-31'
ORDER BY t.country) AS s
GROUP BY country;