我创建了一个请求,它返回具有相同列值的行的ID。例如:
id | Value
______________
1 | label1
2 | label1
3 | label1
4 | label2
5 | label2
我想得到这样的结果:
id | AlternateID | Value
______________________________
1 | 2 | label1
1 | 3 | label1
4 | 5 | label2
到目前为止我得到的最好结果是:
id | AlternateID | Value
______________________________
1 | 2 | label1
2 | 1 | label1
1 | 3 | label1
3 | 1 | label1
4 | 5 | label2
5 | 4 | label2
但正如您所看到的,我在前两列中重复了值
...现在,不使用游标,我被卡住了。
我在SQL Server 2008上。
感谢您的帮助
答案 0 :(得分:2)
使用派生表获取基值并将其连接回原始表。
SELECT
a.id,
b.id as AlternateID,
a.value
FROM
(SELECT MIN(id) as id , value FROM YourTable GROUP BY value) a
JOIN YourTable b on a.value = b.value and a.id <> b.id
答案 1 :(得分:1)
您似乎想要具有相同值的ID对。
with t as (
<your query here>
)
select t1.id as id1, t2.id as id2, t1.value
from t t1 join
t t2
on t1.id < t2.id and t1.value = t2.value;
答案 2 :(得分:0)
先获取最小行,然后获取外连接或外部应用于替代值
SELECT mt.id, mt2.AlternateID, mt.Value
FROM ( SELECT *,
ROW_NUMBER() OVER( PARTITION BY VALUE ORDER BY id ) Rn
FROM myTable
) mt
OUTER APPLY (SELECT id [AlternateID] -- use CROSS APPLY to only return dupes
FROM myTable mt2
WHERE mt2.VALUE = mt.VALUE AND mt2.id <> mt.id) mt2
WHERE Rn = 1