SQL查询来转换表
我遇到了一个问题,看起来像这样
city | distributor | phno --------------------------------- new york xxx 12345 new york yyy 12312 new york zzz 12313 london aaa 12315 london bbb 11111 hong konk ccc 12311
成
city | distributor1 | phno1 | distributor2 | phno2 | distributor3 | phno3 ----------------------------------------------------------------------------- new york xxx 12345 yyy 12312 zzz 12313 london aaa 12315 bbb 11111 0 0 hong konk ccc 12311 0 0 0 0
- 因为任何一个城市都不多,三个分销商
我已经尝试了自我join,但我得到重复的logging,请指教。
让我知道如果这是在Excel中完成? 因为这仅用于报告目的
您也可以在SQL中使用PIVOT表。
我认为这种转变最好在报告作者中完成,而不是在数据库中完成。
我不确定它在Sybase SQL中是否有效,但是我仍然会在其他SQL服务器中以类似的方式开始:
SELECT * FROM (SELECT city FROM table GROUP BY city) AS c LEFT JOIN (SELECT TOP 1 distributor AS distributor1, phno AS phno1 FROM table c1 WHERE c1.city = c.city ORDER BY distributor ASC) AS c1 ON true LEFT JOIN (SELECT TOP 2 distributor AS distributor2, phno AS phno2 FROM table c2 WHERE c2.city = c.city ORDER BY distributor ASC) AS c2 ON distributor1 != distributor2 LEFT JOIN (SELECT TOP 3 distributor AS distributor3, phno AS phno3 FROM table c3 WHERE c3.city = c.city ORDER BY distributor ASC) AS c3 ON distributor1 != distributor3 AND distributor2 != distributor3