学生表
Student Id Student Name
1 Vijay
2 Ram
学生明细表
Student ID Code StudentIdentityNumber
1 Primary 143
1 Secondary 143
1 Teritary 143
2 Primary 123
2 Secondary 123
2 Teritary 126
需要输出
StudentID PrimaryIdentity SecondaryIdentity TeritaryIdentity
2 123 123 126
我只想要这个输出。输出没有StudentID 1,因为对于他来说,主要的次要和相同的数字是相同的。希望很清楚
需要简单的解决方案。是代码列只有三个。仅限静态
答案 0 :(得分:0)
SELECT sd1.Student,
sd1.StudentIdentityNumber as Primary,
sd2.StudentIdentityNumber as Secondary,
sd3.StudentIdentityNumber as Teritary
FROM StudentDetail sd1
JOIN StudentDetail sd2
ON sd1.StudentID = sd2.StudentID
AND sd1.Code = 'Primary'
AND sd2.Code = 'Secondary'
JOIN StudentDetail sd3
ON sd2.StudentID = sd3.StudentID
AND sd2.Code = 'Teritary'
WHERE sd1.Primary <> sd2.Secondary
or sd1.Primary <> sd3.Teritary
答案 1 :(得分:0)
select pvt.StudentID,
pvt.[Primary] PrimaryIdentity,
pvt.Secondary SecondaryIdentity,
pvt.Teritary TeritaryIdentity
from StudentDetail sd
pivot
(
max(StudentIdentityNumber)
for code in ([Primary],Secondary,Teritary)
) as pvt
where pvt.[Primary] <> pvt.Secondary
or pvt.Secondary <> pvt.Teritary
答案 2 :(得分:0)
请查看以下查询: 希望它可以帮到你。
WITH cte
as (SELECT StudentID , [Primary],[Secondary],[Teritary]
FROM
(SELECT
StudentID , Code, StudentIdentityNumber FROM StudentDetail) s
Pivot
( max(StudentIdentityNumber) for Code in ( [Primary],[Secondary],[Teritary]) )as pvt
)
SELECT * FROM cte where cte.[Primary]<>cte.[Secondary] or cte.[Primary]<> cte.Teritary