合并两个select语句进行日期比较

时间:2013-09-26 05:58:21

标签: sql-server tsql select week-number

您好我有以下声明:

DECLARE @currentWEEK INT
DECLARE @previousWEEK INT
DECLARE @CURRENDATE  DATETIME
DECLARE @PREVIOUSDATE  DATETIME

SET @PREVIOUSDATE = YEAR(DATEADD(YEAR, -1, GETDATE()))
SET @CURRENDATE = GETDATE()
SET @currentWEEK = RIGHT(DATENAME(wk,'2013-05-17 00:00:00.000'),2)
SET @previousWEEK = RIGHT(DATENAME(wk,'2012-05-17 00:00:00.000'),2)

SELECT COUNT(*)
FROM vevents 
WHERE RIGHT(DATENAME(wk,dbo.vEvents.DateCreated),2) = @currentWEEK
AND
YEAR(dbo.vEvents.DateCreated) = YEAR(@CURRENDATE)

SELECT COUNT(*)
FROM vevents 
    WHERE RIGHT(DATENAME(wk,dbo.vEvents.DateCreated),2) = @previousWEEK
AND
YEAR(dbo.vEvents.DateCreated) = @PREVIOUSDATE

基本上它比较给定周内两个日期的总数,但我想将给定日期的两个select语句组合起来以返回单个记录集(例如CURRENTYEARCOUNT AND PREVIOUSYEARCOUNT)

非常感谢你的帮助

1 个答案:

答案 0 :(得分:0)

试试这个 -

DECLARE 
      @currentWEEK INT
    , @previousWEEK INT
    , @CURRENDATE DATETIME
    , @PREVIOUSDATE DATETIME

SELECT 
      @PREVIOUSDATE = YEAR(DATEADD(YEAR, -1, GETDATE()))
    , @CURRENDATE = GETDATE()
    , @currentWEEK = RIGHT(DATENAME(wk, '20130517'), 2)
    , @previousWEEK = RIGHT(DATENAME(wk, '20120517'), 2)

SELECT 
      COUNT(CASE WHEN YEAR(e.DateCreated) = @PREVIOUSDATE THEN 1 END)
    , COUNT(CASE WHEN YEAR(e.DateCreated) = YEAR(@CURRENDATE) THEN 1 END)
FROM dbo.vEvents e
WHERE RIGHT(DATENAME(wk, e.DateCreated), 2) = @currentWEEK