0

I'm Trying to select a datetime with a specific year from the table and display the amount of those dates that have that year.

I can select just the year from the datetime, but it gives me the amount of every single specific date, not just the year. Like:

|       Date | Amount |
| 2012-04-07 |      5 |
| 2012-05-21 |      5 |

but I just want 2012, 10.

Select YEAR(Orderdate), count(*)
From Orders
Group by Orderdate

The output needs to show a single row with 2012 in one column, and the total count of 2012's in the second column. Like this:

| Year | Amount |
| 2012 |     10 |
| 2013 |      8 |
| 2014 |      2 |
Johwhite
  • 323
  • 4
  • 18

3 Answers3

3

Use proper date logic in your WHERE clause :

SELECT YEAR(OrderDate) AS [Year],
       COUNT(OrderID) AS Orders --Assumed Column Name
FROM Orders
WHERE OrderDate >= '20120101'
  AND OrderDate < '20130101'
GROUP BY YEAR(OrderDate);

A clause like YEAR(OrderDate) isn't SARGable, meaning that the indexes in your table can't be used. That could have severe implications on your query's performance. As a result using Boolean logic without applying a function to your column in the WHERE is the best choice.

Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
Thom A
  • 88,727
  • 11
  • 45
  • 75
2

For SQL Server;

SELECT YEAR(Orderdate), COUNT(1)
FROM Orders
GROUP BY YEAR(Orderdate)
0

You can achieve it by writing a nested query

SELECT Year , Count(*) AS Total_Count
FROM (Select YEAR(Orderdate) AS Year, *
      From Orders)
WHERE Year = '2012'
GROUP BY Year
umair
  • 525
  • 5
  • 18