问题
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