Fil
Fil

Reputation: 471

Return a string using the month part of a date field

I am trying to create a query which populates the salesPeriod field from the salesDate field. The query should return a string value based on the date part of the salesDate. The conditions are:

If month is equal to equal to 11, 12, 1, return "Christmas Sales"

If month is equal to 6,7,8 return "Summer sales". Otherwise return return "N/A"

Perhaps something like:

salesPeriod: DatePart("month",[salesDate])) = 11 Or 12 Or 1).... or any direction?

Upvotes: 2

Views: 73

Answers (2)

Herr_Razor
Herr_Razor

Reputation: 94

I would also recommend the MONTH() function, which in addition to the other answer can be implemented using the CASE statement.

SQL:

SELECT 
    (CASE
    WHEN MONTH(salesDate) in (11, 12, 1)
        THEN 'Christmas Sales',
    WHEN MONTH(salesDate) in (6, 7, 8)
        THEN 'Summer sales'
    ELSE 
        'N/A'
    END) AS 'Sales Period'

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269873

You can use the month() function and conditional logic. Here is one method:

select iif(month(salesDate) in (11, 12, 1), "Christmas Sales",
           iif(month(salesDate) in (6, 7, 8), "Summer sales", "N/A")
          ) as salesPeriod

Upvotes: 2

Related Questions