我正在使用sql server 2014。我对一个表(t1)运行了下面的t-sql查询。表t1摘录如下:
ID N1 N2 N3 N4 N5 N6
1 2 10 12 25 29 30
2 10 13 23 24 35 39
3 1 20 23 26 32 40
4 5 9 11 12 28 35
...
预期产量:
我希望查询的输出能够找到当前[id]的值[n1]到[n6]是否存在于上面2个[id]级别的任何值中。
为了简化,查询需要找出[id]=4处的值([n1]到[n6])是否存在于[id]-2处的值中;等于[id]=2
ID N1 N2 N3 N4 N5 N6 N1_ID-2 N2_ID-2 N3_ID-2 N4_ID-2 N5_ID-2 N6_ID-2
1 2 10 12 25 29 30 0 0 0 0 0 0
2 10 13 23 24 35 39 0 0 0 0 0 0
3 1 20 23 26 30 40 0 0 0 0 1 0
4 5 9 11 13 28 35 0 0 0 1 0 1
...
目前我的问题如下:
USE MyDatabase
SELECT *,
(CASE WHEN [N1] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N1_ID-2],
(CASE WHEN [N2] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N2_ID-2],
(CASE WHEN [N3] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N3_ID-2],
(CASE WHEN [N4] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N4_ID-2],
(CASE WHEN [N5] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N5_ID-2],
(CASE WHEN [N6] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N6_ID-2]
FROM [T1]
运行上述代码集时会显示以下错误消息:
当子查询没有引入exists时,只能在选择列表中指定一个表达式。
如何更正代码以避免此错误?
2条答案
按热度按时间szqfcxe21#
可以使用self-join和
IN
这样地:798qvoo82#