Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Where Clause

Tags:

sql

sql-server

SELECT DISTINCT Campaign_id 
FROM Impressions 
WHERE Date BETWEEN '2015-03-01' AND '2015-03-31' ;

The above query gives me the result for the Campaign_id's that have been active on any date between 2015-03-01 and 2015-03-31.

I want the result set to contain the campaign_id's if the have been active on all the dates in between 2015-03-01 and 2015-03-31.

How would I go about this?

like image 356
Tauseef Hussain Avatar asked Jun 21 '15 15:06

Tauseef Hussain


1 Answers

Assuming DATE is a DATE datatype and has no time component.

DECLARE @Start DATE = '2015-03-01',
        @End   DATE = '2015-03-31'

SELECT Campaign_id
FROM   Impressions
WHERE  Date BETWEEN @Start AND @End
GROUP  BY Campaign_id
HAVING COUNT(DISTINCT Date) = 1 + DATEDIFF(DAY, @Start, @End); 

Or a version without the variables

SELECT Campaign_id
FROM   Impressions
       CROSS APPLY (VALUES ({ d '2015-03-01' },
                            { d '2015-03-31' })) V([Start], [End])
WHERE  [Date] BETWEEN [Start] AND [End]
GROUP  BY Campaign_id, [Start], [End]
HAVING COUNT(DISTINCT Date) = 1 + DATEDIFF(DAY, [Start], [End]); 
like image 97
Martin Smith Avatar answered Sep 24 '22 17:09

Martin Smith