我需要根据另一个关系值查询同一列中的不同值。
表格设置如下:athleteID,meetName,eventName,score
事件都是一样的,但有不同的会面,我的查询需要返回:help,event,score from meetName ='whatever1',得分来自meetname ='whatever2'
我尝试了完成此操作的所有基本方法,但无法做到。我最后一次试过
SELECT distinct athleteID, event,
(select score from performances where meetName='Snowflake') as SnowScore,
(select score from performances where meetName='Valentine') as ValScore,
from performances
where event='high jump'
返回:单行子查询返回多行
我的预期结果是这样的:
aid, event, SnowScore, ValScore
1 , high jump, 6, 8
2 , high jump, 3, 5
3, high jump, 8, 10
答案 0 :(得分:1)
不规定RDMS,我的答案是SQL Server:
如果你想使用子查询,你需要引用atherleteID和eventName,如果有多个结果(不清楚你的问题,但我认为atheletes在多次会议上竞争),你需要聚合。
可能有更好的方法,但作为简单的一次性查询,我可能会这样做:
SELECT athleteID, eventName,
sum(CASE WHEN meetName='Snowflake' THEN score ELSE 0 END) as SnowScore,
sum(CASE WHEN meetName='Valentine' THEN score ELSE 0 END) as ValScore
FROM performances
GROUP BY atheleteID,eventName
更好的长期解决方案是使用PIVOT,如果meetNames会随着时间的推移而改变,您可以创建动态数据透视查询,我发现的一个很好的例子是here
答案 1 :(得分:0)
没试过,但它提出了想法......:
SELECT athleteID, event,
sum(case when meetName='Snowflake' then score else 0 end) as SnowScore,
sum(case when meetName='Valentine' then score else 0 end) as ValScore,
from performances
group by athleteID, event
答案 2 :(得分:0)
我想补充一点,自然内部联接是基本(非商业)sql应该在这里完成的。
语法将是:select * from (subquery1) NIJ (subquery2)
子查询语法:
select athleteID, score as ValScore from performances, NIJ athletes where meet =‘Valentin’ and event=‘beam’
和
select athleteID, score as SnowScore from performances, NIJ athletes where meet =‘SnowFlake’ and event=‘beam’