我有一个如下的StudentDetails表:
和StudentResults表如下:
我想构建一个输出以下内容的查询:
因此,我希望以非规范化的方式组合这两个表的数据。我尝试过使用PARTITION BY和Pivot,但我还没有能够接近结果。是否有一种简单的方法来进行此查询?感谢
答案 0 :(得分:2)
为每个字词执行left join
:
select d.StudentId, d.Name, d.Course, r1.result as Term1Result, r2.result as Term2Result
from StudentDetails d
left join StudentResults r1 on d.StudentId = r1.StudentId and r1.term = 1
left join StudentResults r2 on d.StudentId = r2.StudentId and r2.term = 2
答案 1 :(得分:1)
试试这个。
SELECT *
FROM
(
SELECT sd.StudentID,
sd.Name,
sd.Course,
'Term' + '' + CONVERT(VARCHAR(10),sr.Term) + '' + 'Result' AS Term
sr.Result
FROM StudentDetails sd
INNER JOIN StudentResults sr
ON sr.StudentID = sd.StudentID
) AS Data
PIVOT
(
MAX(Result) FOR Term IN ([Term1Result], [Term2Result])
) AS pvt
答案 2 :(得分:1)
试
select d.*,
case when r.term=1 then result end as term1result,
case when r.term=2 then result end as term2result,
from StudentDetails d join StudentResults r on
d.StudentId = r.StudentId
答案 3 :(得分:1)
这就是所谓的pivot
问题。有几种方法可以解决它。 SQL Server甚至有special feature for it。
基本想法是group by
要折叠行,而filtered
聚合:
SELECT StudentID
, MAX(CASE WHEN term = 1 THEN result END) Term1Result
, MAX(CASE WHEN term = 2 THEN result END) Term2Result
FROM StudentResults
GROUP BY StudentID
然后可以将此结果连接到StudentDetails。
以下是我在SQL中针对数据透视问题撰写的文章:
答案 4 :(得分:1)
SELECT d.StudentId, d.Name, d.Course, max(case when r.term =1 then result else null end) as Term1Result, max(case when r.term =2 then result else null end) as Term2Result
FROM StudentDetails d
LEFT JOIN StudentResults r on d.StudentId = r.StudentId
GROUP BY d.StudentId, d.Name, d.Course