假设我有下表(实际上这是查询的结果)
我想要的是提出下表
除了第一个代码值之外,它为每个代码值分配零。
任何策略都可以吗?
提前致谢
答案 0 :(得分:3)
这有帮助吗?
declare @tab table(
code int,
amount int)
insert into @tab values
(1,100),
(1,100),
(1,100),
(2,500),
(2,500),
(3,1000);
select code,
case when rn=1 then
amount
else 0 end amount
from
(select *,
row_number()Over(partition by code Order by amount) RN
from @tab)t
答案 1 :(得分:1)
您可以使用row_number()
标识每个code
的第一行。从那以后,它只是一个简单的case
表达式:
SELECT code, CASE rn WHEN 1 THEN amount ELSE 0 END AS amount
FROM (SELECT code, amount,
ROW_NUMBER() OVER (PARTITION BY code ORDER BY amount) AS rn
FROM my_table)
答案 2 :(得分:1)
试试这个
SELECT Code,CASE When RN > 1 Then 0 Else Amount
FROM
(
SELECT *,ROW_NUMBER() OVER (Partition by Code Order by (Select Null)) RN
FROM Table1
) AS T
答案 3 :(得分:0)
请尝试:
select Code,
case when ROW_NUMBER() over (partition by Code Order by Amount)=1 then Amount else 0 end Amount
From YourTable
答案 4 :(得分:0)
请在下面的查询中用帐户更新表格:
SELECT A.code,
( CASE
WHEN A.rno = 1 THEN B.amount
ELSE 0
END ) AS amount
FROM (SELECT Row_number()
OVER(
partition BY code
ORDER BY code DESC) AS rno,
code
FROM account) AS A
LEFT OUTER JOIN (SELECT C.code,
Sum(C.amount) AS amount
FROM account C
GROUP BY C.code) AS B
ON B.code = A.code