在SQL中编写CASE语句以包含多个列

时间:2014-07-01 19:44:10

标签: mysql sql

我有一个相当简单的查询,如下所示:

SELECT
  max(case when site_id = 1 then cast(REPLACE(REPLACE(REPLACE(salary, '$',''),' ',''), ',', '') as UNSIGNED) end) fd_salary,
  max(case when site_id = 2 then cast(REPLACE(REPLACE(REPLACE(salary, '$',''),' ',''), ',', '') as UNSIGNED) end) dd_salary,
  max(case when site_id = 3 then cast(REPLACE(REPLACE(REPLACE(salary, '$',''),' ',''), ',', '') as UNSIGNED) end) ss_salary
FROM mytable 
WHERE gamedate = '2014-07-01'
GROUP BY player_id;

这是按预期工作的。我在salary中有一个mytable列,当我运行我的select语句时,我正试图将salaries的所有player_id放到一行中,因为现在它们已存储在他们自己的行中。我的问题如下:除salary之外,如何在此select语句中再添加一列?除了position列之外,我还希望能够对salary列执行相同的操作。我不确定我是否可以将它混合到现有的case语句中,或者我是否必须为每个玩家添加三个case语句。如果我没有将它与salary结合使用,它可能看起来像:

SELECT max(case when site_id = 1 then position end) fd_position, ...

等。有没有办法将这些组合成一个查询?

3 个答案:

答案 0 :(得分:2)

尽管它的外观,case标量函数,它评估为单个标量值。我自己,因为我讨厌重复打字,我会做这样的事情:

select t.player_id ,
       max( case t.site_id when 1 then t.salary   else 0 end ) as fd_salary   ,
       max( case t.site_id when 1 then t.position else 0 end ) as fd_position ,
       max( case t.site_id when 2 then t.salary   else 0 end ) as dd_salary   ,
       max( case t.site_id when 2 then t.position else 0 end ) as dd_position ,
       max( case t.site_id when 3 then t.salary   else 0 end ) as ss_salary   ,
       max( case t.site_id when 3 then t.position else 0 end ) as ss_position
from ( select player_id ,
              site_id   ,
              gamedate  ,
              cast(REPLACE(REPLACE(REPLACE(salary,'$',''),' ',''), ',', '') as UNSIGNED) as salary ,
              cast(position as UNSIGNED) as position
       from mytable
     ) t
where t.gamedate = '2014-07-01'
  and t.side_id between 1 and 3
group by t.player_id

答案 1 :(得分:0)

你尝试过这个:

 SELECT
max(case when site_id = 1 then cast(REPLACE(REPLACE(REPLACE(salary, '$',''),' ',''), ',', '') as UNSIGNED) end) fd_salary,
max(case when site_id = 2 then cast(REPLACE(REPLACE(REPLACE(salary, '$',''),' ',''), ',', '') as UNSIGNED) end) dd_salary,
max(case when site_id = 3 then cast(REPLACE(REPLACE(REPLACE(salary, '$',''),' ',''), ',', '') as UNSIGNED) end) ss_salary,
max(case when site_id = 1 then position end) fd_position,
max(case when site_id = 2 then position end) dd_position,
max(case when site_id = 3 then position end) ss_position
from ....

答案 2 :(得分:0)

问:有没有办法将这些组合成一个查询?

A: SELECT列表中返回的每一列都是一个单独的表达式。

CASE表达式返回单个值。

您将使用单独的CASE表达式返回fd_position列,就像您的示例所示。

(这是SQL的限制,而不仅仅是MySQL。)