SQL Query获取和更新今天和昨天的数据?

时间:2010-12-10 17:46:01

标签: sql sql-server-2005

好吧,我必须创建一个类似的表格结构,以便更简化 -

Test_Table: EmployeeId,Points,Date
Test_Table1:Score,EmployeeId,Date
Leaderboards_Table: Points,Score,EmployeeId,Day,Month,Year

现在我需要编写一个查询来更新或插入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

现在上面的查询只更新今天...我想做的事情也是昨天更新 也在一个查询中我不想写另一个查询....所以无论如何要做一个查询来更新昨天和今天的点。

UPDATE :此查询也会被多次调用..因此,为此提供性能最高的查询会很棒。

2 个答案:

答案 0 :(得分:1)

如果更改为连接而不是子查询,则会更容易。

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

答案 1 :(得分:0)

这是一个使用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'