还是行转列的问题。数据出来了,但是不是在同一行,不知道那里出错了 :(
要查询的表
select qid,cid,pid,QuotePrice from quote
qid cid pid QuotePrice ----------- ----------- ----------- ----------------------------------------------------- 3 3 6 500.04 2 7 1000.05 3 8 1500.06 1 6 1000.07 2 6 8000.08 1 7 500.010 1 8 1000.011 2 8 5000.012 2 11 500.013 1 11 1000.014 3 11 1500.015 1 10 500.016 1 12 500.017 4 6 1111.018 4 7 1111.019 2 10 131.020 3 10 123.0(所影响的行数为 17 行)
select qID,cid,pid, max(case px when 1 then cid else '' end) 'comName1', max(case px when 1 then QuotePrice else '' end) 'Price1', max(case px when 2 then cid else '' end) 'comName2', max(case px when 2 then QuotePrice else '' end) 'Price2', max(case px when 3 then cid else '' end) 'comName3', max(case px when 3 then QuotePrice else '' end) 'Price3'from (select top 1000 px=(select count(1) from quote where pid=a.pid and QuotePrice<a.QuotePrice)+1 ,* from quote as a order by pid,QuotePrice) as tgroup by qid,cid,pid,QuotePrice
qID cid pid comName1 Price1 comName2 Price2 comName3 Price3--- ---- ---- -------- ------ -------- ------- -------- -------3 3 6 3 500.0 0 0.0 0 0.06 1 6 0 0.0 1 1000.0 0 0.017 4 6 0 0.0 0 0.0 4 1111.07 2 6 0 0.0 0 0.0 0 0.08 1 7 1 500.0 0 0.0 0 0.04 2 7 0 0.0 2 1000.0 0 0.018 4 7 0 0.0 0 0.0 4 1111.010 1 8 1 1000.0 0 0.0 0 0.05 3 8 0 0.0 3 1500.0 0 0.011 2 8 0 0.0 0 0.0 2 5000.020 3 10 3 123.0 0 0.0 0 0.019 2 10 0 0.0 2 131.0 0 0.015 1 10 0 0.0 0 0.0 1 500.012 2 11 2 500.0 0 0.0 0 0.013 1 11 0 0.0 1 1000.0 0 0.014 3 11 0 0.0 0 0.0 3 1500.016 1 12 1 500.0 0 0.0 0 0.0(所影响的行数为 17 行)
--因为你的QID是不重复的 你GROUP BY QID 就会全部显示出来--你这样试一下select max(qID),cid,pid, max(case px when 1 then cid else '' end) 'comName1', max(case px when 1 then QuotePrice else '' end) 'Price1', max(case px when 2 then cid else '' end) 'comName2', max(case px when 2 then QuotePrice else '' end) 'Price2', max(case px when 3 then cid else '' end) 'comName3', max(case px when 3 then QuotePrice else '' end) 'Price3'from (select top 1000 px=(select count(1) from quote where pid=a.pid and QuotePrice<a.QuotePrice)+1 ,* from quote as a order by pid,QuotePrice) as tgroup by cid,pid