简体   繁体   English

SQL将结果分为2列

[英]SQL divide results into 2 columns

I have a question about retrieving data using SQL 我有一个关于使用SQL检索数据的问题

i want to get 我想得到

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

in one query to get the output like this: 在一个查询中获得如下输出:

year12_comments  |  year13_comments
7                |  8         

I hope its clear. 我希望清楚。

Like this 像这样

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

Update: 更新:

If you want to get the percentage between them, you can enclose them in a subquery like this: 如果要获取它们之间的百分比,可以将它们包含在子查询中,如下所示:

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 UPDATE2

If you want to make the year12_comments, year13_comments as well as the percentage new column, just include them in the SELECT statement like this: 如果要创建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,

If you are using MS SQL Server 2005 or above, you can use PIVOT 如果您使用的是MS SQL Server 2005或更高版本,则可以使用PIVOT

Unless you can use the PIVOT function @HamletHakobyan suggested, IMHO this is a bad decision. 除非您可以使用PIVOT函数@HamletHakobyan建议,否则恕我直言,这是一个错误的决定。 Unless (another) end of the World happens in 2013, you'll have to do this for 2014 too. 除非世界另一端发生在2013年,否则您也必须在2014年这样做。 I'd rather go with a simple group by for the user and the year too: 我也希望为用户和年份使用一个简单的分组依据:

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

Sure, you'll have to code a bit in your application, but from a clarity aspect, this seems to be the way to go... 当然,您必须在应用程序中编写一些代码,但是从清晰度的角度来看,这似乎是可行的方法...

(BTW I think this will be quicker than the CASE WHEN structure too...) (顺便说一句,我认为这也比CASE WHEN结构还要快...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM