我能够查询一个条件(如下图所示),但是当我查询几个标准并尝试使用不同的标准创建同一个表的两个相同列时,我得不到任何结果。第二张图像是我无法检索的预期结果。任何输入都受到高度赞赏。谢谢。
select save_line from save_output_table
where execution_id in ('292')
and seq_id = '0'
and save_type='R'
order by line_id ASC
+------------+
| Save_line |
+------------+
| 17 |
| 22 |
| 23 |
+------------+
SELECT
( select save_line
from save_output_table
where execution_id in ('292')
and seq_id = '0'
and save_type='R'
order by line_id ASC
) as save_line1,
( select save_line
from save_output_table
where execution_id in ('286')
and seq_id = '0'
and save_type='R'
order by line_id ASC
) as save_line2
from save_output_table
+-------------+------------+
| Save_line 1 | Save_line2 |
+-------------+------------+
| 17 | 9 |
| 22 | 5 |
| 23 | 3 |
+-------------+------------+
示例数据:
+---------------+--------+-----------+---------+-----------+
| execution_id | seq_id | save_type | line_id | save_line |
+---------------+--------+-----------+---------+-----------+
| 286 | 0 | R | 1 | 17 |
| 286 | 0 | R | 2 | 22 |
| 286 | 0 | R | 3 | 23 |
| 286 | 0 | D | 1 | 17 |
| 286 | 0 | D | 2 | 22 |
| 286 | 0 | D | 3 | 23 |
| 292 | 0 | R | 1 | 9 |
| 292 | 0 | R | 2 | 5 |
| 292 | 0 | R | 3 | 3 |
| 292 | 0 | D | 1 | 98 |
| 292 | 0 | D | 2 | 622 |
| 292 | 0 | D | 3 | 273 |
+---------------+--------+-----------+---------+-----------+
答案 0 :(得分:1)
因此,如果您想按行line_id按顺序列出save_line,则根据save_type和execution_id在不同的列中,您需要进行透视。有几种不同的方法可以做到这一点。无论您使用什么样的SQL,这里都有一些应该可以工作:
SELECT line_id,
max(CASE WHEN execution_id = '292' and save_type = 'R' then save_line end) R_292,
max(CASE WHEN execution_id = '286' and save_type = 'R' then save_line end) R_286
FROM save_output_table
GROUP BY line_id
或
SELECT t1.save_line save_line1,
t2.save_line save_line2
FROM
(SELECT *
FROM save_output_table
WHERE save_type = 'R'
and execution_id = '292'
) t1
JOIN (SELECT *
FROM save_output_table
WHERE save_type = 'R'
and execution_id = '286'
) t2
ON t1.line_id = t2.line_id
注意:对于第二个选项,如果每个条件的line_id数相同,则join仅提供完整列表。如果没有,则应将其更改为FULL OUTER JOIN,这在MySQL和其他可能无法使用。