Mysql 在SQL中编写CASE语句以包含多列
我有一个相当直截了当的查询,如下所示:Mysql 在SQL中编写CASE语句以包含多列,mysql,sql,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
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;
这正是我们想要的。我在mytable
中有一个salary
列,我试图在运行select语句时将player\u id
的所有salary
放在一行中,因为现在它们都存储在自己的行中。我的问题是:除了薪水
之外,如何在这个select语句中再添加一列?除了工资
列之外,我还希望能够对职位
列进行同样的操作。我不确定我是否可以将它混合到现有的case语句中,或者是否必须为每个玩家添加三个case语句。如果我没有将它与薪水
结合起来,它可能看起来像:
SELECT max(case when site_id = 1 then position end) fd_position, ...
等等。有没有办法将这些内容组合成一个查询?您是否尝试过以下方法:
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 ....
尽管它看起来很像,
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
Q:有没有一种方法可以将这些信息合并到一个查询中 A:选择列表中返回的每一列都是一个单独的表达式
CASE
表达式返回单个值
您可以使用一个单独的CASE
表达式返回fd_position
列,如示例所示
(这是SQL的限制,不仅仅是MySQL。)不要存储货币符号。。。或者任何数字格式。