这是我的第一篇文章,我希望一切都会清楚。我有桌子,如:
client ; cost
Paula ; 100
Paula ; 50
Jacob ; 300
Paula ; 120
我想添加另一个列“client2”,其中如果没有重复值,则值为1,或者如果有重复,则应该仅为具有最大成本的副本执行1,因此:
client ; cost ; client2
Paula ; 100 ; 0
Paula ; 50 ; 0
Jacob ; 40 ; 1
Paula ; 120 ; 1
在真实表格中有2000条记录。我应该如何在SQL Server中编写它?提前致谢, 保
答案 0 :(得分:4)
WITH CTE AS
(SELECT
client,
cost,
ROW_NUMBER() OVER (PARTITION BY client ORDER BY cost DESC) AS RowNo
FROM
table)
SELECT
client,
cost,
CASE RowNo
WHEN 1 THEN 1
ELSE 0
END AS client2
FROM
CTE;
答案 1 :(得分:0)
您可以使用cursor
执行此操作。以下示例应该处理您想要的内容。您必须将#table替换为您的表名。像罪一样丑陋但它有效;)
CREATE TABLE #Table
(
client NVARCHAR(100),
cost int,
client1 int
);
INSERT INTO #Table
VALUES
('Paula',100,null),
('Paula',50,null),
('Jacob',300,null),
('Paula',120,null);
DECLARE @clientColumn nvarchar(100);
DECLARE @Dup int;
DECLARE client_cursor CURSOR FOR
SELECT client,cost FROM #Table ORDER BY client,cost
OPEN client_cursor;
FETCH NEXT FROM client_cursor INTO @clientColumn
WHILE @@FETCH_STATUS=0
BEGIN
set @dup = (SELECT TOP 1 cost FROM #Table WHERE client = @clientColumn GROUP BY client ORDER BY cost desc )
UPDATE #Table
SET
client1 = 1
WHERE client = @clientColumn AND cost = @dup
FETCH NEXT FROM client_cursor INTO @clientColumn
END
CLOSE client_cursor
DEALLOCATE client_cursor;
UPDATE #Table
SET
client1 = 0
WHERE client1 IS NULL
SELECT * FROM #Table