-1

Query Q1 gives me table in which there is total count of file received for particular date in a country.

Q1:

select
  b.country,
  CAST(a.ProcessDate AS Date) AS DATE,
  count(a.ProcessDate) AS total
from Log a
LEFT JOIN Files b ON a.FileID = b.FileID
where a.ProcessDate BETWEEN '2022-10-01' AND '2022-10-30'
GROUP BY
  b.Country,
  CAST(a.ProcessDate AS DATE)

Now I want this table to transform into below table based on date column as header and also count of files should be distributed based on country like below table:

I need SQL for transforming Q1 to above table format. I was trying to use Pivot but not able to write correct sql which will give desire output.

AKHIL OMAR
  • 47
  • 6
  • Sounds like a job for your reporting/presentation software rather than SQL Server. But see https://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query – Charlieface Nov 08 '22 at 13:55

1 Answers1

1

Pivot's simple syntax makes for hard to write columns.

Here is a short example.

with t (Country ,Date,total)
as
(
Select  'newzealand'                 ,    '2022-10-03',21
Union ALL Select 'argentina'         ,    '2022-10-04',5
Union ALL Select 'brazil'            ,    '2022-10-04',4
Union ALL Select 'chile'             ,    '2022-10-05',22
Union ALL Select 'mexico'            ,    '2022-10-05',34
Union ALL Select 'peru'              ,    '2022-10-06',1

)

Select 
    *
from
    (
Select 
    Date,
    Total,
    Country
from t
    ) x
Pivot(
    sum(total)
    for Date in (
            [2022-10-03],
            [2022-10-04],
            [2022-10-05],
            [2022-10-06]
    )
) as pivottable

You can then make this example dynamic, it is best to read the post for this, it is explained very well in it.

SQL Server dynamic PIVOT query?

Stigi
  • 104
  • 3
  • How to get dates of last 30 days dynamically using sql. You have provided hard coded values but when I try to get the dates usin sql, I am getting error. – AKHIL OMAR Nov 14 '22 at 11:44