我正在寻找一种在条件
上更新某些表行的方法我的旧查询就像:
update Database1.dbo.Table1
set Database1.dbo.Table1.AllVisit = (select COUNT(ID) from Database1.dbo.Table2 WHERE UserID = Database1.dbo.Table1.UserID group by UserID)
现在我想只更新table1的最后一天fileds而不是更新所有主题 这个查询可以使用吗?
update Database1.dbo.Table1
set Database1.dbo.Table1.AllVisit = (select COUNT(ID) from Database1.dbo.Table2 WHERE UserID = Database1.dbo.Table1.UserID And UserDate between
DATEADD(day, -1, convert(date, GETDATE())) and convert(date, GETDATE()) group by UserID)
或者这个:
update Database1.dbo.Table1
set Database1.dbo.Table1.AllVisit = (select COUNT(ID) from Database1.dbo.Table2 WHERE UserID = Database1.dbo.Table1.UserID And UserDate between
DATEADD(day, -1, convert(date, GETDATE())) and convert(date, GETDATE()) group by UserID) Where
Database1.dbo.Table1.UserDate between
DATEADD(day, -1, convert(date, GETDATE())) and convert(date, GETDATE()))
答案 0 :(得分:1)
你去......
update A set A.AllVisit = (select COUNT(ID) from Database1.dbo.Table2 WHERE UserID = A.UserID And convert(varchar(100),UserDate,101) = convert(varchar(100),getdate()-1,101) ) FROM Database1.dbo.Table1 A
答案 1 :(得分:1)
使用表结构:
create table Table1 (AllVisit int, UserDate datetime , UserID int)
insert into Table1 values (0,GETDATE()-1,1),(0,GETDATE()-1,2),(0,GETDATE()-1,3);
create table Table2 (ID int,UserID int,UserDate datetime)
insert into Table2 values (1,1,GETDATE()-1),(2,1,GETDATE()-1),(3,1,GETDATE()-1),(4,1,GETDATE()-1),(5,3,GETDATE()-1);
如下所示的update
查询将起作用:
update T1
SET T1.AllVisit = isnull(T3.idCount ,0)
FROM Table1 T1
CROSS APPLY (select COUNT(T2.ID) AS idCount
from Table2 T2
WHERE T2.UserID = T1.UserID
And convert(date,T2.UserDate) = DATEADD(day, -1, convert(date, GETDATE())) -- convert UserDate column to date type if it's a datetime
group by T2.UserID)T3
WHERE convert(date,T1.UserDate) = DATEADD(day, -1, convert(date, GETDATE()))