[英]SQL Query to get and update today and yesterday's data?
Alright, I have to create a similar table structure to mine more simplified - 好吧,我必须创建一个类似的表结构来简化我的工作-
Test_Table: EmployeeId,Points,Date
Test_Table1:Score,EmployeeId,Date
Leaderboards_Table: Points,Score,EmployeeId,Day,Month,Year
Now I need to write a single query to update or insert into LeaderBoards_Table something like - 现在,我需要编写一个查询来更新或插入LeaderBoards_Table之类的东西-
UPDATE Leaderboards_Table
SET Points=pts,Score=total_score
FROM
(
(SELECT
(SELECT SCORE from Test_Table1 WHERE Employee = @EmployeeId AND DAY(DATE)=10 AND MONTH(DATE)=12 AND YEAR(DATE)=2010) as pts
)
Points as pts
from Test_Table where Employee = @EmployeeId AND DAY(DATE)=10 AND MONTH(DATE)=12 AND YEAR(DATE)=2010
)
WHERE EmployeeId=@EmployeeId and DAY=10 AND MONTH=12 AND YEAR=2010
Now the above query only updates for today...what I want to do is also update yesterday also in a single query I dont want to write another query....so is there anyway to do a single query to update yesterday and today's points. 现在上面的查询只更新今天...我想做的也是昨天也更新一次,我也不想写另一个查询....所以无论如何都可以做一个查询来更新昨天和今天的点。
UPDATE : Also this query will be called lot of times..so it would be great to have the most performance effective query for this. 更新 :此查询也将被调用很多次。因此,对此进行性能最有效的查询将非常好。
Its a lot easier if you change to joins instead of subqueries. 如果更改为联接而不是子查询,则容易得多。
UPDATE Leaderboards_Table
SET
Points=t1.score,
Score=total_score
FROM
Leaderboards_Table lt
INNER JOIN Test_Table1 t1
ON lt.employee_ID = t1.employee_id
INNER JOIN Test_Table t
ON lt.employee_ID = t1.employee_id
and lt.date = t1.date
WHERE
EmployeeId=@EmployeeId and DAY IN (9,10) AND MONTH=12 AND YEAR=2010
Here's a solution that uses the BETWEEEN clause. 这是使用BETWEEEN子句的解决方案。
UPDATE Leaderboards_Table
SET Points=tt.Points, Score = tt1.Score
FROM LeaderBoards_Table
JOIN Test_Table1 tt1 ON LeaderBoards_Table.EmployeeId = tt1.EmployeeId
JOIN Test_Table tt ON tt1.EmployeeId = tt.EmployeeId
WHERE EmployeeId = @EmployeeId
AND CONVERT(datetime CAST(YEAR AS varchar) + CAST(MONTH AS varchar) + CAST(DAY AS varchar))
BETWEEN '20101209' AND '20101210'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.