[英]SQL query same column twice
I need to query the same column for different values depending on another relational value. 我需要根据另一个关系值在同一列中查询不同的值。
Table is set up like this : athleteID, meetName, eventName, score 表格设置如下:田径ID,meetName,eventName,得分
Events are all the same but there are Different Meets and my query needs to return: aid, event, score from meetName = 'whatever1', score from meetname = 'whatever2' 事件都是一样的,但是有不同的聚会,我的查询需要返回:援助,事件,meetName ='whatever1'的得分,meetname ='whatever2'的得分
Ive tried every basic way about completeing this but cannot do it. 我已经尝试了完成此操作的所有基本方法,但无法做到。 I've lastly tried
我终于尝试了
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'
which returns: single-row subquery returns more than one row 返回:单行子查询返回多个行
My expected result would be like this: 我的预期结果将是这样的:
aid, event, SnowScore, ValScore
1 , high jump, 6, 8
2 , high jump, 3, 5
3, high jump, 8, 10
Does not stipulate RDMS, my answer is with SQL Server: 没有规定RDMS,我的答案是使用SQL Server:
If you wanted to use a subquery you need to reference the atherleteID and eventName, also if there were more than one result (not clear from your question but I assume atheletes compete at multiple meets) you would need to aggregate. 如果要使用子查询,则需要引用atherleteID和eventName,并且如果结果不止一个(您的问题尚不清楚,但我假设运动员们在多次比赛中竞争),则需要进行汇总。
There may be a better way but as a simple one off query I would probably do it like: 也许有更好的方法,但是作为一个简单的关闭查询,我可能会这样做:
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
A better longer term solution would be with PIVOT and if the meetNames will change over time you can create dynamic pivot queries, a good example I found is here 更好的长期解决方案是使用PIVOT,如果metNames随时间变化,您可以创建动态数据透视查询,我在这里找到了一个很好的例子
Didn't try it but it gives the idea... : 没有尝试过,但是它给出了主意...:
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
I would like to add that Natural Inner Join is what should've been done here for basic(non-commercial) sql. 我想补充一点,对于基本(非商业)sql,应该在此处进行自然内部联接。
Syntax would've been: select * from (subquery1) NIJ (subquery2)
语法应该是:
select * from (subquery1) NIJ (subquery2)
The subqueries syntax: 子查询语法:
select athleteID, score as ValScore from performances, NIJ athletes where meet =‘Valentin’ and event=‘beam’
and 和
select athleteID, score as SnowScore from performances, NIJ athletes where meet =‘SnowFlake’ and event=‘beam’
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.