我有一对多的关系。我想用父记录在一行中显示我的孩子记录这里是我的查询LIKE数据透视表我想显示学生在1行考试中获得的分数,这取决于在表1中注册了多少考试,我有父ID和表2我有考试子组件,如
父母考试viva和子组件viva 1和viva 2
现在学生查询将有2列exam1标记和考试2分标记,这是1个考试中的两个标记所以这将是单行像
student | viva 1 | viva 2
我的主要考试ID是1,组件viva 1和viva 2 ID是21,22
现在用两个ID标记保存在标记表中我现在想要在单行中查看它们在考试的标记中是什么?和viva 2标记???
SELECT DISTINCT
A.S_RNo, A.S_SNo, C.S_SName, G.S_RID, A.Crs_SID, A. Enr_ID,
0 AS M_ObtMarks
FROM
tblAcdEnrol_Course A
INNER JOIN
tblAcdStudent_Reg G ON A.S_RNo = G.S_RNo
INNER JOIN
tblAcdStudent C ON A.S_SNo = C.S_SNo
LEFT OUTER JOIN
tblAExPolicy_1 D ON A.ESec_T_ID = D.ESec_T_ID
LEFT OUTER JOIN
tblAExPolicy_2 E ON D.AEx_ID = E.AEx_ID
CROSS APPLY
(SELECT DISTINCT
A.S_RNo, A.S_SNo, S_SName, S_RID, Crs_SID, B.AEx2_ID,
C.ESec_T_ID, Enr_ID, ISNULL(M_ObtMarks, 0) AS M_ObtMarks
FROM
tblAExMarks_1 A
INNER JOIN
tblAExPolicy_2 B ON A.AEx2_ID = B.AEx2_ID
INNER JOIN
tblAExPolicy_1 C ON B.AEx_ID = C.AEx_ID
INNER JOIN
tblAcdStudent_Reg D ON A.S_RNo = D.S_RNo
INNER JOIN
tblAcdEnrol_Course E ON E.S_RNo = A.S_RNo
INNER JOIN
tblAcdStudent F ON F.S_SNo = A.S_SNo)V
WHERE
V.ESec_T_ID = 6
AND V.Crs_SID <> 2
AND V.AEx2_ID = 1
不工作
目前
1 21 5.0
1 21 10.0
1 21 10.0
2 21 4.0
2 21 10.0
2 21 8.0
我想要
1 21 5.0 10.0 10.0
2 21 4.0 10.0 8.0
图片
答案 0 :(得分:0)
您可以在输出数据上使用pivot,如下所示:
;with cte as (
SELECT DISTINCT A.S_RNo , A.S_SNo, C.S_SName, G.S_RID,A.Crs_SID , A. Enr_ID,0 AS M_ObtMarks,
RowN = Row_number() over (Partition by A.S_RNo, A.S_SNo order by A.S_RNo)
FROM tblAcdEnrol_Course A
INNER JOIN tblAcdStudent_Reg G ON A.S_RNo = G.S_RNo
INNER JOIN tblAcdStudent C ON A.S_SNo = C.S_SNo
LEFT OUTER JOIN tblAExPolicy_1 D ON A.ESec_T_ID = D.ESec_T_ID
LEFT OUTER JOIN tblAExPolicy_2 E ON D.AEx_ID = E.AEx_ID
CROSS APPLY (
SELECT DISTINCT A.S_RNo , A.S_SNo, S_SName, S_RID, Crs_SID ,B. AEx2_ID , C.ESec_T_ID , Enr_ID,ISNULL(M_ObtMarks , 0) AS M_ObtMarks
from tblAExMarks_1 A
inner join tblAExPolicy_2 B on A.AEx2_ID = B.AEx2_ID
inner join tblAExPolicy_1 C on B.AEx_ID = C.AEx_ID
inner join tblAcdStudent_Reg D ON A.S_RNo = D.S_RNo
INNER JOIN tblAcdEnrol_Course E ON E.S_RNo = A.S_RNo
INNER JOIN tblAcdStudent F ON F.S_SNo = A.S_SNo)V
WHERE V.ESec_T_ID = 6 AND V.Crs_SID <> 2 and V.AEx2_ID = 1
)
select * from cte
pivot (max(M_ObtMarks) for RowN in ([1],[2],[3]) ) p