-1

I've got a table with vehicles mark and sales date. I need to take a query to take how many different vehicles has been sold in this year, separated by months, for example:

      | January | February | March | April |..............
----------------------------------------------------------
mark1 |         |     1    |   5   |       |..............
mark2 |   45    |          |       |   7   |..............
mark3 |   12    |    11    |   5   |   3   |..............

The original table is:

    mark    |    soldDate
----------------------------
    mark1   |  01/07/2020
    mark2   |  04/07/2020
    mark1   |  05/07/2020
    mark3   |  06/07/2020

If i want to take how many different vehicles has been sold i use this query:

SELECT mark, COUNT(mark) WHERE FORMAT(soldDate, 'MMMM') = 'january' GROUP BY mark

How can i divide the data in every single month?

usr1990
  • 21
  • 2
  • 7
  • you want the output as shown? if yes please share the raw data. – lovish kumar Jul 06 '20 at 14:37
  • 2
    What does the data in your table(s) look like? What are *you* tried, and why didn't it work? What is your question? – Thom A Jul 06 '20 at 14:39
  • The original table has a row for every vehicle sold and the sold date if i want to take the vehicles sold in a month: select mark, count(mark) as 'vehicles' where format(soldDate, 'MMMM') = 'JANUARY' group by mark – usr1990 Jul 06 '20 at 14:40
  • Does this answer your question? [Convert Rows to columns using 'Pivot' in SQL Server](https://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) – Filburt Jul 06 '20 at 14:45

2 Answers2

0

With conditional aggregation:

select mark, 
  count(case when month(soldDate) = 1 then 1 end) as January,
  count(case when month(soldDate) = 2 then 1 end) as February,
  ...........................................................
where year(soldDate) = 2020 
group by mark 
forpas
  • 160,666
  • 10
  • 38
  • 76
0
SELECT Mark, DATENAME(MONTH, DATEADD(MONTH, MONTH(SalesDate) - 1, '1900-01-01')) M, COUNT(*) COUNT
FROM VehicleSales  
WHERE YEAR(SalesDate) = '2020' 
GROUP BY Mark, MONTH(SalesDate)
Order by Mark, M