Dani
Dani

Reputation: 5

SQL based on my Example for Month

I am new to SQL and Learning on my own. I was wondering if someone can help guiding me to a write SQL.

I have the below data:

Sample

I am using the following query:

SELECT 
    TIMESTAMP
    DATEPART(Year, TIMESTAMP) Year, 
    DATEPART(Month, TIMESTAMP) Month, 
    COUNT(*) [Total Rows]
FROM 
    stage.ACTIVITY_ACCUMULATOR_archive
WHERE 
    TIMESTAMP BETWEEN '01-Jan-2014' AND '30-June-2014'
GROUP BY 
    DATEPART(Year, TIMESTAMP), DATEPART(Month, TIMESTAMP)
ORDER BY 
    Year, Month

What I am trying to achieve is to display the Timestamp with year and month between the certain date and group them by month and year.

I get an error:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Year'

Upvotes: 1

Views: 60

Answers (1)

vamsi
vamsi

Reputation: 352

This should work.There was a extra timestamp column in select list.

SELECT  
    DATEPART(Year, TIMESTAMP) Year, 
    DATEPART(Month, TIMESTAMP) Month, 
    COUNT(*) [Total Rows]
FROM 
    stage.ACTIVITY_ACCUMULATOR_archive
WHERE 
    TIMESTAMP BETWEEN '01-Jan-2014' AND '30-June-2014'
GROUP BY 
    DATEPART(Year, TIMESTAMP), DATEPART(Month, TIMESTAMP)
ORDER BY 
    Year, Month

Upvotes: 1

Related Questions