SQL将结果分为2列

时间:2013-01-10 11:18:32

标签: sql

我有一个关于使用SQL检索数据的问题

我想要

count(comments_id) where comment_year = 2012 and 
count(comments_id) where comment_year = 2013 

在一个查询中获取如下输出:

year12_comments  |  year13_comments
7                |  8         

我希望它清楚。

3 个答案:

答案 0 :(得分:4)

喜欢这个

...
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

UPDATE2

如果您想制作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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

除非你能使用PIVOT函数@HamletHakobyan建议,恕我直言这是一个糟糕的决定。除非(另一个)世界末日发生在2013年,否则你也必须在2014年这样做。对于用户和年份,我宁愿选择一个简单的小组:

SELECT user_id, comment_year, count(1)
FROM mytable
GROUP BY user_id, comment_year

当然,你需要在你的应用程序中编写一些代码,但从清晰的角度来看,这似乎是要走的路......

(顺便说一句,我认为这也会比CASE WHEN结构更快......)