我有一张这样的表:
+----------+---------+
| ipiresia | program |
+----------+---------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
| 4 | 1 |
| 4 | 2 |
+----------+---------+
我想进行查询以转换表格,如下所示:
+----------+----------+----------+----------+
| ipiresia | program1 | program2 | program3 |
+----------+----------+----------+----------+
| 1 | x | x | x |
| 2 | x | x | x |
| 3 | x | x | x |
| 4 | x | x | |
+----------+----------+----------+----------+
我使用过这个查询,但它不起作用:
SELECT ipiresia, (CASE program WHEN '1' THEN 'x' ELSE NULL) AS program1, (CASE program WHEN '2' THEN 'x' ELSE NULL) AS program2, (CASE program WHEN '3' THEN 'x' ELSE NULL) AS program3 FROM table GROUP BY ipiresia
感谢任何帮助。
答案 0 :(得分:1)
似乎与我足够相似,但无论如何......
SELECT ipiresia
, MAX(CASE WHEN program = 1 THEN 'x' ELSE '' END) program1
, MAX(CASE WHEN program = 2 THEN 'x' ELSE '' END) program2
, MAX(CASE WHEN program = 3 THEN 'x' ELSE '' END) program3
FROM my_table
GROUP
BY ipiresia;
就个人而言,我不会这样做 - 更愿意在可能的情况下处理应用程序级代码中的数据显示问题。