我希望我的代码看起来像这样:
publshrID BkID_Title BkID_Title BkID_Title BkID_Title
---- ---- ------ ------ -------
9000 1502 Book#1 1301 Book#2 1101 Book#3 1402 Book#4
9042 1304 Book#1 1201 Book#2 1101 Book#3 1402 Book#4
这是我写的代码
WITH BKS AS(
SELECT ROW_NUMBER() over(partition by pb.publ_id order by BK.list_price DESC) AS RankN,
PB.publ_id AS publ,
CONVERT(varchar(25),book_id)+ ' '+ title AS Main
FROM bkinfo.publishers AS PB
INNER JOIN bkinfo.books AS BK ON PB.publ_id = BK.publ_id
)
SELECT BKS.publ,
CASE WHEN RankN = 1 THEN MAIN ELSE '' END AS a,
CASE WHEN RankN = 2 THEN MAIN ELSE '' END AS b,
CASE WHEN RankN = 3 THEN MAIN ELSE '' END AS c,
CASE WHEN RankN = 4 THEN MAIN ELSE '' END AS d
FROM BKS
这不太对劲。我究竟做错了什么?
答案 0 :(得分:2)
尝试:
WITH BKS AS(
SELECT ROW_NUMBER() over(partition by pb.publ_id order by BK.list_price DESC) AS RankN,
PB.publ_id AS publ,
CONVERT(varchar(25),book_id)+ ' '+ title AS Main
FROM bkinfo.publishers AS PB
INNER JOIN bkinfo.books AS BK ON PB.publ_id = BK.publ_id
)
SELECT BKS.publ,
max(CASE WHEN RankN = 1 THEN MAIN END) AS a,
max(CASE WHEN RankN = 2 THEN MAIN END) AS b,
max(CASE WHEN RankN = 3 THEN MAIN END) AS c,
max(CASE WHEN RankN = 4 THEN MAIN END) AS d
FROM BKS
GROUP BY BKS.publ