我有一个包含Date
列和Amount
列的表:
CustID Date Amount
1 20150301 10000
1 20150302 5000
1 20150303 15000
2 20150208 9000
2 20150201 5000
2 20150202 6000
我希望Amount
在某个日期之后设置为Date
。更新后,它应如下所示:
CustID Date Amount
1 20150301 10000
1 20150302 0
1 20150303 0
2 20150208 0
2 20150201 5000
2 20150202 0
我该怎么做?
答案 0 :(得分:2)
我会使用窗口函数来执行此操作:
with toupdate as (
select t.*, min(date) over (partition by CustId) as mindate
from table t
)
update toupdate
set amount = 0
where date > mindate;
答案 1 :(得分:0)
您可以使用以下查询检查date
是否不等于MIN(Date)
:
UPDATE Mytable
SET Amount = 0
FROM Mytable AS t
WHERE [date] <> (SELECT MIN([Date])
FROM Mytable
WHERE CustId = t.CustID)
或者使用CTE
:
;WITH MIN_CTE AS (
SELECT MIN([Date]) AS MinDate, CustID
FROM Mytable
GROUP BY CustID
)
UPDATE Mytable
SET Amount = 0
FROM Mytable AS t
INNER JOIN MIN_CTE AS c ON t.CustID = c.CustID
WHERE t.[Date] <> c.MinDate
答案 2 :(得分:0)
我们可以做更新但是在这里我在select语句中显示相同的row_number和MIN函数...
declare @t table (custid int,datet date,Amount int)
insert into @t(custid,datet,Amount)values (1,'20150301',10000)
insert into @t(custid,datet,Amount)values (1,'20150302',5000)
insert into @t(custid,datet,Amount)values (1,'20150303',15000)
insert into @t(custid,datet,Amount)values (2,'20150208',9000)
insert into @t(custid,datet,Amount)values (2,'20150201',5000)
insert into @t(custid,datet,Amount)values (2,'20150202',4000)
;with CTE AS
(
select *,ROW_NUMBER()OVER(PARTITION BY custid order by datet )RN from @t
)
Select custid,datet,case when RN = 1 then amount ELSE 0 END Amt from cte
OR
;with CTE AS
(
select *,min(datet)OVER(PARTITION BY custid )RN from @t
)
Select custid,datet,case when RN = MIN(datet) then amount ELSE 0 END Amt from cte
group by custid,datet,Amount,RN