我有一个关于使用 SQL 检索数据的问题
我想得到
count(comments_id) where comment_year = 2012 and
count(comments_id) where comment_year = 2013
在一个查询中获得如下输出:
year12_comments | year13_comments
7 | 8
我希望它清楚。
我有一个关于使用 SQL 检索数据的问题
我想得到
count(comments_id) where comment_year = 2012 and
count(comments_id) where comment_year = 2013
在一个查询中获得如下输出:
year12_comments | year13_comments
7 | 8
我希望它清楚。
像这样
...
SUM(CASE WHEN comment_year = 2012 THEN 1 ELSE 0 END) AS year12_comments,
SUM(CASE WHEN comment_year = 2013 THEN 1 ELSE 0 END) AS year13_comments,
...
更新:
如果要获取它们之间的百分比,可以将它们包含在子查询中,如下所示:
SELECT
(year12_comments / year13_comments) * 100
FROM
(
SELECT
...
SUM(CASE WHEN comment_year = 2012 THEN 1 ELSE 0 END) AS year12_comments,
SUM(CASE WHEN comment_year = 2013 THEN 1 ELSE 0 END) AS year13_comments,
...
) sub
如果您想创建year12_comments, year13_comments
以及百分比新列,只需将它们包含在如下SELECT
语句中:
SELECT
year12_comments,
year13_comments,
(year12_comments / year13_comments) * 100 AS ThePercenatge
FROM
(
SELECT
...
SUM(CASE WHEN comment_year = 2012 THEN 1 ELSE 0 END) AS year12_comments,
SUM(CASE WHEN comment_year = 2013 THEN 1 ELSE 0 END) AS year13_comments,
...
) sub
COUNT(CASE WHEN comment_year = 2012 THEN 1 END) year12_comments,
COUNT(CASE WHEN comment_year = 2013 THEN 1 END) year13_comments,
如果您使用MS SQL Server 2005
或以上,您可以使用PIVOT
除非您可以使用 @HamletHakobyan 建议的 PIVOT 功能,否则恕我直言,这是一个错误的决定。除非(另一个)世界末日发生在 2013 年,否则 2014 年你也必须这样做。我宁愿为用户和年份使用一个简单的 group by:
SELECT user_id, comment_year, count(1)
FROM mytable
GROUP BY user_id, comment_year
当然,您必须在应用程序中编写一些代码,但从清晰的角度来看,这似乎是要走的路……
(顺便说一句,我认为这也会比CASE WHEN
结构更快......)