[英]Writing a CASE statement in SQL to include multiple columns
我有一個相當簡單的查詢,看起來像以下內容:
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_id
所有salaries
都放入一行,因為現在它們存儲在自己的行中。 我的問題如下:除salary
外,我如何在此選擇語句中再增加一列? 除了salary
欄外,我還希望對position
欄進行相同的操作。 我不確定是否可以將其混入現有的案例陳述中,或者是否必須為每個玩家添加三個以上的案例陳述。 如果我不將其與salary
結合起來,它可能看起來像:
SELECT max(case when site_id = 1 then position end) fd_position, ...
等。有沒有一種方法可以將它們組合成一個查詢?
盡管看起來很像,但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
你試過這個嗎:
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 ....
問:有沒有一種方法可以將它們組合成一個查詢?
答: SELECT列表中返回的每一列都是一個單獨的表達式。
CASE
表達式返回單個值。
如示例所示,您將使用單獨的CASE
表達式返回fd_position
列。
(這是SQL的局限性,而不僅僅是MySQL。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.