我得到了“学生”表格,如下所示:
ReposeBuffer
我正在尝试旋转桌子但没有得到它。
我也在Stackoverflow中进行了搜索,但是我认为期望的输出是不同的,所以找不到合适的查询。
这是预期的输出:
student | section
-----------+-----------------
john | Ace
jack | Newbie
kiya | Top
BRET | Top
Scott | Top
Stephen | Ace
Fran | Ace
Chris | Good
Kathleen | Good
Rick | Newbie
答案 0 :(得分:1)
使用条件聚合:
SELECT
MAX(CASE WHEN section = 'Ace' THEN student END) Ace,
MAX(CASE WHEN section = 'Top' THEN student END) Top,
MAX(CASE WHEN section = 'Newbie' THEN student END) Newbie,
MAX(CASE WHEN section = 'Good' THEN student END) Good
FROM students
GROUP BY student
ORDER BY student
如果您实际上想在没有匹配项而不是'N/A'
值的情况下在结果集中看到NULL
,请使用COALESCE()
(或RDBMS的等效项):
SELECT
COALESCE(MAX(CASE WHEN section = 'Ace' THEN student END), 'N/A') Ace,
COALESCE(MAX(CASE WHEN section = 'Top' THEN student END), 'N/A') Top,
COALESCE(MAX(CASE WHEN section = 'Newbie' THEN student END), 'N/A') Newbie,
COALESCE(MAX(CASE WHEN section = 'Good' THEN student END), 'N/A') Good
FROM students
GROUP BY student
ORDER BY student