I have a SQL query that includes a __DATE__ macro. A Python script replaces this macro with the current date and then the statement is executed thus giving one day's worth of data.
- For the first item selected, I would like to use
tblLabTestResult.CollectionDateinstead of__DATE__. - I would like to include the prior 7 days instead of just the current day.
- The desired output would be something similar to:
Date,Result,Total
2021-08-28,Detected,5
2021-08-28,Not Detected,9
2021-08-29,Detected,23
2021-08-29,Not Detected,6
2021-08-30,Detected,88
2021-08-30,Not Detected,26
Current query:
SELECT
'__DATE__' as Date,
tblLabTestResult.Result as Result,
Count(tblLabTestResult.Result) as Total
FROM
PncRegDb.dbo.tblLabTestResult as tblLabTestResult
WHERE
tblLabTestResult.TestName like '%cov%'
AND tblLabTestResult.TestName not like '%aoe%'
AND tblLabTestResult.TestName not like '%antibody%'
AND tblLabTestResult.CollectionDate >= '__DATE__'
AND tblLabTestResult.CollectionDate <= '__DATE__ 11:59:59 PM'
GROUP BY
tblLabTestResult.Result;
How can I change my SQL query to accommodate these requirements? I am using MS SQL Server.
CASEexpression (not sure what you mean by "first item") 2.DATEADD(day, -7....Note that you really shouldn't have scripts doing find/replace, use proper parameterization instead, see stackoverflow.com/questions/7505808/…. AlsotblLabTestResultis a very long alias, try to make it more readable with something a bit shorter__DATE__as DateSELECT tblLabTestResult.CollectionDate as DateI'm striggling to understand what problems you are having here, please be clear?tblLabTestResult.CollectionDateis invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Also my knowledge of SQL is limited on how to fix this.