0
/*-------------temp table--------------*/
CREATE TEMPORARY TABLE IF NOT EXISTS bowlpick.tempschedule AS

(SELECT * FROM bowlpick.schedule

where season = (select max(year) from bowlpick.season));
/*-------------temp table--------------*/

set @g1= (select winner from bowlpick.tempschedule where game =1);

select date,name, @g1,bowl1 Pick,comf1

,case 
    when bowl1 =  @g1 then  comf1 
    when bowl1 <> @g1 then -comf1 
else '0' end pts

from bowlpick.picks
where year(date) = (select max(year) from bowlpick.season)
order by bowl1 desc limit 5



<--------------------Table----------------->
  name      @g1            Pick       comf1 pts
Player 1    Boise State     Washington  7   -7
Player 2    Boise State     Boise State 30  -30
Player 3    Boise State     Boise State 21  -21
Player 4    Boise State     Boise State 27  -27
Player 5    Boise State     Boise State 15  -15

为什么这不起作用???最后四个点应该是正数,而不是负数。就好像变量(@g1)在“CASE”部分不起作用。当“选择”部分时它可以正常工作。如果我对获胜者(博伊西州)进行硬编码,它会正常工作。变量在 case 语句中不起作用吗?

4

1 回答 1

0

不知道为什么要使用临时表,您可以在单个查询中执行此操作,请参阅以下示例以从某个地方开始,我注意到的另一件事是 case 为两个 case 语句返回数字,为 else 返回一个字符串. 不仅如此,case 语句还有 2 个WHEN语句覆盖了所有基数,这意味着无论如何都不会选择“0”。

SELECT 
    bowlpick.picks.date
    ,bowlpick.picks.name
    ,bowlpick.tempschedule.winner
    ,bowlpick.picks.bowl1 Pick
    ,bowlpick.picks.comf1
    ,CASE 
        WHEN bowlpick.picks.bowl1 =  bowlpick.tempschedule.winner  THEN bowlpick.picks.comf1 
        WHEN bowlpick.picks.bowl1 <> bowlpick.tempschedule.winner  THEN -bowlpick.picks.comf1 
        ELSE 0
    END pts
FROM 
    bowlpick.picks
    LEFT JOIN bowlpick.tempschedule ON year(bowlpick.picks.date) = bowlpick.tempschedule.season 
WHERE 
    bowlpick.tempschedule.game =1
ORDER BY 
    bowl1 DESC
LIMIT 5

以下是一项额外的工作,消除了对临时表的需求(链接和分组需要更好地定义,但对于不完整的架构,这是我能做的最好的)

SELECT 
    p.Date
    ,p.Name
    ,s.Winner
    ,p.Bowl1 Pick
    ,p.Comf1
    ,CASE 
        WHEN p.Bowl1 =  s.Winner  THEN p.Comf1 
        WHEN p.Bowl1 <> s.Winner  THEN -p.Comf1 
        ELSE 0
    END pts
FROM 
    picks p
    LEFT JOIN schedule s ON YEAR(p.Date) = s.Season 
WHERE 
    s.game = 1
GROUP BY 
    s.Season, p.Date
HAVING
    s.Season = MAX(s.Season)
ORDER BY 
    p.Bowl1 DESC
LIMIT 5

他是我用来做这个的SQL Fiddle

于 2013-11-11T16:39:38.260 回答