使用SQL查询对数据进行非规范化

时间:2016-06-23 14:22:47

标签: sql sql-server

我有一个如下的StudentDetails表:

enter image description here

和StudentResults表如下:

enter image description here

我想构建一个输出以下内容的查询:

enter image description here

因此,我希望以非规范化的方式组合这两个表的数据。我尝试过使用PARTITION BY和Pivot,但我还没有能够接近结果。是否有一种简单的方法来进行此查询?感谢

5 个答案:

答案 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