SELECT
st.suniq,
sd.firstname,
sd.lastname,
tD.testuniq,
- CASE WHEN (td.subtestc)='LI' THEN st.testscore END AS [CELDT Listening],
--CASE WHEN (td.subtestc)='SP' THEN st.testscore END AS [CELDT Speaking],
--CASE WHEN (td.subtestc)='RD' THEN st.testscore END AS [CELDT Reading],
--CASE WHEN (td.subtestc)='WR' THEN st.testscore END AS [CELDT Writing],
--CASE WHEN (td.subtestc)='TO' THEN st.testscore END AS [CELDT Overall],
td.testc,
td.subtestc,
zst.descript,
st.takendt,
st.grdlvl,
st.testscore
FROM dbo.stutests st
JOIN dbo.testdef td ON td.testuniq=st.testuniq
JOIN studemo sd ON sd.suniq=st.suniq
JOIN zsubtest zst ON zst.subtestc=td.subtestc
WHERE tscrtypc='S'
AND td.testc='CELDT'
AND takendt LIKE '%2013%';
结果如下
suniq firstname lastname subtestc descript grdlvl testscore
254585 Brenda Cazares LI CELDT Listening 8 534
254585 Brenda Cazares SP CELDT Speaking 8 612
254585 Brenda Cazares RD CELDT Reading 8 571
254585 Brenda Cazares WR CELDT Writing 8 680
254585 Brenda Cazares WR CELDT overall 8 710
我希望每个人都没有空值
suniq firstname lastname Listening Speaking Reading Writing Overall grdlve
254585 Brenda Cazares 534 612 571 680 710 8
当我构建case语句时,它给了我null。我想我需要一个枢轴和案例陈述的组合。任何人都有任何建议和提前感谢。
答案 0 :(得分:0)
SELECT suniq ,
firstname ,
lastname ,
COALESCE([LI], 0) AS Listening ,
COALESCE([SP], 0) AS Speaking ,
COALESCE([RD], 0) AS Reading ,
COALESCE([WR], 0) AS Writing ,
COALESCE([TO], 0) AS Overall ,
st.grdlvl
FROM ( SELECT st.suniq ,
sd.firstname ,
sd.lastname ,
tD.testuniq ,
td.subtestc ,
td.testc ,
td.subtestc ,
zst.descript ,
st.takendt ,
st.grdlvl ,
st.testscore
FROM dbo.stutests st
JOIN dbo.testdef td ON td.testuniq = st.testuniq
JOIN studemo sd ON sd.suniq = st.suniq
JOIN zsubtest zst ON zst.subtestc = td.subtestc
WHERE tscrtypc = 'S'
AND td.testc = 'CELDT'
AND takendt LIKE '%2013%'
) T PIVOT ( SUM(testscore) FOR [subtestc] IN ( [LI], [SP], [RD], [WR],
[TO] ) ) AS Pvt
答案 1 :(得分:0)
你几乎只需将case statement
包裹在Max aggregate
SELECT st.suniq,
sd.firstname,
sd.lastname,
Max(CASE WHEN td.subtestc = 'LI' THEN st.testscore END) AS [Listening],
Max(CASE WHEN td.subtestc = 'SP' THEN st.testscore END) AS [Speaking],
Max(CASE WHEN td.subtestc = 'RD' THEN st.testscore END) AS [Reading],
Max(CASE WHEN td.subtestc = 'WR' THEN st.testscore END) AS [Writing],
Max(CASE WHEN td.subtestc = 'TO' THEN st.testscore END) AS [Overall],
st.grdlvl,
FROM dbo.stutests st
JOIN dbo.testdef td
ON td.testuniq = st.testuniq
JOIN studemo sd
ON sd.suniq = st.suniq
JOIN zsubtest zst
ON zst.subtestc = td.subtestc
WHERE tscrtypc = 'S'
AND td.testc = 'CELDT'
AND takendt LIKE '%2013%'
GROUP BY st.suniq,
sd.firstname,
sd.lastname,
st.grdlvl