我有一张包含以下记录的表
id name city
1 aaa NY
2 bbb NY
3 ccc LA
4 ddd LA
5 eee NY
我希望通过比较“城市”列来为表添加额外的列。 col4中的值对于'city'列中的每个唯一值应为'1',对于'city'列中的重复值应为'0'。
id name city col4
1 aaa NY 1
2 bbb NY 0
3 ccc LA 1
4 ddd LA 0
5 eee NY 0
我希望得到一些帮助。
由于
答案 0 :(得分:1)
Select id, name, city
, Case
When Exists( Select 1
From Table As T1
Where T1.Id < T.Id
And T1.city = T.city ) Then 0
Else 1
End As Col4
From Table As T
答案 1 :(得分:0)
这将为您提供比子查询更好的性能,子查询一次针对外部查询中的每一行运行:
DECLARE @YourTable table (id int, name varchar(5), city varchar(5))
INSERT @YourTable VALUES (1,'aaa','NY')
INSERT @YourTable VALUES (2,'bbb','NY')
INSERT @YourTable VALUES (3,'ccc','LA')
INSERT @YourTable VALUES (4,'ddd','LA')
INSERT @YourTable VALUES (5,'eee','NY')
SELECT
y.id, y.name, y.city
,CASE
WHEN y.ID=dt.MinID THEN 1
ELSE 0
END AS col4
FROM @YourTable y
INNER JOIN (SELECT
City, MIN(id) AS MinID
FROM @YourTable
GROUP BY City
) dt ON y.City=dt.City
ORDER BY id
输出:
id name city col4
----------- ----- ----- -----------
1 aaa NY 1
2 bbb NY 0
3 ccc LA 1
4 ddd LA 0
5 eee NY 0
(5 row(s) affected)