I am attempting to 'compact' a bit of a TSQL query but getting massively differing results telling me that something is amiss.
The original query which gave OK results more in line with what I expected to see was:
DECLARE @start_date date
DECLARE @end_date date
SET @start_date = '01-01-2022'
SET @end_date = '12-31-2022'
SELECT d.DESCRIPTION,
sum(amount) as TOTAL
FROM tbEXPENSES as e
INNER JOIN tbDESCRIPT as d ON e.DESCRIPT_ID=d.ID
WHERE REC_DATE BETWEEN @start_date AND @end_date
AND e.DESCRIPT_ID IN ('81', '83', '86', '87', '88', '89', '90', '91', '92', '93', '97', '98', '99',
'100', '101', '107', '108', '109', '111', '146', '161', '166', '176', '181',
'182', '186', '187', '191', '197', '198', '199', '200', '201', '211', '216',
'221', '246', '256', '271', '276', '280', '281', '286', '311', '317', '416',
'435', '446', '451', '461', '466', '471', '476', '481', '491', '492', '496',
'497', '501', '503', '506', '511', '516', '521', '523', '526', '527', '531',
'532', '551', '556', '561', '562', '563', '571', '581', '586', '611', '621',
'626', '631', '636', '641', '646', '655', '661', '666', '667', '681', '696',
'706', '711', '730', '731', '732', '740', '741', '742', '743', '744', '745',
'746', '747')
GROUP BY DESCRIPTION
ORDER BY DESCRIPTION
The second TSQL one I attempted gives crazy high numbers and that one is:
DECLARE @start_date date
DECLARE @end_date date
SET @start_date = '01-01-2022'
SET @end_date = '12-31-2022'
SELECT d.DESCRIPTION,
sum(amount) as TOTAL
FROM tbEXPENSES as e
INNER JOIN tbDESCRIPT as d ON e.DESCRIPT_ID=d.ID
WHERE REC_DATE BETWEEN @start_date AND @end_date
AND e.DESCRIPT_ID BETWEEN '81' AND '221'
OR e.DESCRIPT_ID BETWEEN '461' AND '546'
OR e.DESCRIPT_ID BETWEEN '266' AND '296'
OR e.DESCRIPT_ID BETWEEN '551' AND '563'
OR e.DESCRIPT_ID BETWEEN '676' AND '706'
OR e.DESCRIPT_ID BETWEEN '740' AND '747'
OR e.DESCRIPT_ID IN ('246', '256', '311', '317', '416', '435', '451', '571', '581',
'586', '611', '621', '626', '631', '636', '641', '646', '655',
'661', '666', '667', '711', '730', '731', '732')
GROUP BY DESCRIPTION
ORDER BY DESCRIPTION
I would like to condense my SQL a bit but something is definitely not correct. Am I using the OR
statement correctly? Can someone point me in the correct direction please?
The @start_date
and @end_date
are parameters I pass via the program. I have hard coded it here for ease of understanding.