我是sql server的新手,所以我真的很难在这个领域翻译我的oracle sql。通常在oracle sql中我会在我的“in”子句中使用两个项目,但我想在sql server中可能效果不好?
这是我的数据:
a_id | idxno | note_text
1 0 text 1 for item b_id = 61
2 1 text 2 for item b_id = 61
3 0 text 1 for item b_id = 71
4 1 text 2 for item b_id = 71
5 2 text 3 for item b_id = 71
6 0 text 1 for item b_id = 81
7 0 text 1 for item b_id = 91
8 1 text 2 for item b_id = 91
a_id | b_id
1 61
2 61
3 71
4 71
5 71
6 81
7 91
8 91
(**注意:我不能保证max(a_id)是notes_table中的max(idxno))
b_id | item_desc
61 desc of item 61
71 desc of item 71
81 desc of item 81
91 desc of item 91
我希望从笔记表中显示具有最大音符的项目的报告。如下所示:
b_id | item_desc | note
61 desc of item 61 text 2 for item b_id = 61
71 desc of item 71 text 3 for item b_id = 61
81 desc of item 81 text 1 for item b_id = 61
91 desc of item 91 text 2 for item b_id = 61
我尝试过:
select item_table.b_id, item_table.item_desc,
from item_table, notes_bridge_table
where item_table.b_id = notes_bridge_table.b_id
and notes_bridge_table.a_id in
(select a_id from notes_table
where notes_table.a_id = notes_bridge_table.a_id
and notes_table.idxno, notes_table.a_id in
(select max(idxno), a_id from notes_table group by a_id))
但是“and notes_table.idxno,notes_table.a_id in”的倒数第二行似乎对sql server无效。
答案 0 :(得分:2)
此查询(在Oracle中)
select * from t
where ( x, y ) in ( select x, y from t1 );
可以转换为在MS-SQL上运行的相关子查询:
select * from t
where exists (
select 1 from t1
where t1.x = t.x and t1.y = t.y
);
以下是Oracle的演示:http://www.sqlfiddle.com/#!4/2300d/2
对于MS_SQL:http://www.sqlfiddle.com/#!3/2300d/2
答案 1 :(得分:1)
为何复杂化?它可以简化:
SELECT i.b_id, i.item_desc, n.note_text
FROM item_table AS i INNER JOIN notes_bridge_table AS b
ON i.b_id = b.b_id
INNER JOIN notes_table n ON b.a_id = n.a_id
INNER JOIN
(SELECT b_id, MAX(idxno) AS idxno
FROM notes_table AS n INNER JOIN notes_bridge_table AS b
ON n.a_id = b.a_id
GROUP BY b.b_id) AS b2
ON b.b_id = b2.b_id AND b2.idxno = n.idxno
并且......所有复杂性都来自完全冗余的a_id
列。你的桌面结构不是最好的。
顺便说一句,第3列在您的示例中没有显示正确的b_id
。这是正确的输出:
b_id item_desc note_text
------ ------------------ ---------------------------
61 desc of item 61 text 2 for item b_id = 61
71 desc of item 71 text 3 for item b_id = 71
81 desc of item 81 text 1 for item b_id = 81
91 desc of item 91 text 2 for item b_id = 91