user3259628
user3259628

Reputation: 5

SQL Querying by a specific month

I'm doing some homework and part of a question is asked like so: "a list of assists open in the month of December 2004"

I've got a majority of a subquery down for paring down what else is required, however I'm coming up short with a way to only get results specifically from only December '04, regardless of when the OpenDate is. I've been unable to get the OpenDate field to play nicely with DATEPART(Month,x) in my query because of the above restriction of it not mattering when it was opened.

The following is the Assists table.

CREATE TABLE Assists
(
AssistID            INT             IDENTITY    NOT NULL    PRIMARY KEY, 
OpenDate            DATE            NOT NULL    DEFAULT GETDATE(), 
CloseDate           DATE            NULL, 
ContactType         VARCHAR(15)     NOT NULL,
ReferralSource      VARCHAR(60)     NULL,
RefPhone            VARCHAR(10)     NULL,
RefConfidential     BIT             NULL,
RefFollowUpNeeded   BIT             NULL,
AssistType          VARCHAR(55)     NOT NULL,
SpecialistID        INT             NOT NULL
    CONSTRAINT fk_Assists_Specialists   FOREIGN KEY (SpecialistID)  REFERENCES Specialists(SpecialistID),
ClientID            INT             NOT NULL
    CONSTRAINT fk_Assists_Clients       FOREIGN KEY (ClientID)      REFERENCES Clients(ClientID),
CONSTRAINT ck_Assists_OpenDate  CHECK (OpenDate <= GETDATE()),
CONSTRAINT ck_Assists_CloseDate CHECK (CloseDate <= GETDATE()),
CONSTRAINT ck_Assists_RefPhone CHECK (RefPhone LIKE REPLICATE('[0-9]',10)),
)

Any help is much appreciated.

Upvotes: 0

Views: 60

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97331

I think these are the conditions you should be looking at:

  • OpenDate is in or before December 2004 AND
  • CloseDate is either NULL OR is in or after December 2004

SELECT *
FROM Assists
WHERE OpenDate <= '20041231'
AND (CloseDate IS NULL OR CloseDate >= '20041201')

Upvotes: 1

Related Questions