SQL知识初学者
我有一张下表:ScoreTable
Name Score Reason Subject
a1 0 NULL NULL
a2 -1 NULL NULL
a3 -3 fail Maths
a4 -3 fail History
a3 0 NULL NULL
我想写一个查询,看起来像下面的
Select DISTINCT Name, Result,
(If Result = -3
then Concat(Reason,' ',Subject))As FailedIn)
来自ScoreTable
预期产出:
Name Score FailedIn
a1 0 0
a2 -1 0
a3 -3 fail Maths
a4 -3 fail History
答案 0 :(得分:0)
你可能不想放" 0"和同一列中的字符串。最好使用NULL
。所以:
Select Name, Result,
(case when Result = -3 then Reason + ' ' + Subject
end) as FailedIn
目前还不清楚为什么最后一行会消失,但也许你想要这样的东西:
Select Name, min(Result),
(case when min(Result) = -3 then max(Reason + ' ' + Subject)
end) as FailedIn
from table t
group by name
答案 1 :(得分:0)
尝试使用CASE..WHEN..THEN如下,并使用最低结果得分:
SELECT Name, MIN(Result)
CASE WHEN Result = -3
THEN Reason +' '+Subject
ELSE Result
END As FailedIn
FROM mytable
GROUP BY Name, Result
答案 2 :(得分:0)
试试这个
SELECT NAME,SCORE, 如果分数= -3那么CONCAT(原因,'',主题) ELSE' 0' 从ScoreTable结束为FAILEDIN