Combine two select statements for date comparison

北战南征 提交于 2019-12-13 01:26:39

问题


Hi I have the following statement:

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

Essentially it compares a total for two dates within a given week, but I would like to combine the two select statements for given dates to return a single record set(eg CURRENTYEARCOUNT AND PREVIOUSYEARCOUNT)

Many thanks for your help


回答1:


Try this one -

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


来源:https://stackoverflow.com/questions/19020441/combine-two-select-statements-for-date-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!