Raj 0203[
^] wrote in the comment to the solution #1:
Please Re-Check my Output, as it was having two Header Rows ,
As i mentioned in the comment to the question, you can't achieve that using T-SQL only. You need reporting tools, such as
ReportViewer[
^],
CrystalReports[
^], etc.
Using T-SQL only, you can achieve a result set with single header, i.e.:
| Loc | sts | Jan-16 | Mar-16 | May-16 |
-------------------------------------
| Hyd | A | 1 | 0 | 0 |
| Hyd | B | 2 | 0 | 0 |
| Vjd | A | 0 | 1 | 0 |
| Vjd | B | 0 | 1 | 0 |
| Viz | A | 0 | 0 | 1 |
| Viz | B | 0 | 0 | 1 |
or
| Loc | Date | A | B | C |
-----------------------------
| Hyd | Jan-16 | 1 | 0 | 0 |
| Hyd | Mar-16 | 0 | 0 | 0 |
| Hyd | May-16 | 1 | 2 | 1 |
or a mixed content like:
| Loc | Jan-16_A | Jan-16_B | Jan-16_C | Mar-16_A | Mar-16_B | Mar_16_C | ... and so on...
-------------------------------------------------------------------------------
| Hyd | 1 | 0 | 0 | 2 | 0 | 0 | ...
| Vjd | ..
| Viz | ...
but, i do not recommend to use such of view due to performance issues.
[EDIT]
As per your wish...
SET DATEFORMAT dmy;
CREATE TABLE #tmp
(
Loc VARCHAR(5),
[Date] Date,
Id INT,
Sts VARCHAR(5)
);
INSERT INTO #tmp (Loc, [Date],Id, Sts)
VALUES ('Hyd', '15-01-2016', '1', 'A'),
('Vjd', '16-01-2016', 2, 'B'),
('Viz', '15-01-2016', 3, 'C'),
('Hyd', '15-03-2016', 4, 'A'),
('Vjd', '15-03-2016', 5, 'B'),
('Viz', '15-03-2016', 6, 'C'),
('Hyd', '15-03-2016', 4, 'A'),
('Vjd', '15-05-2016', 5, 'B'),
('Viz', '15-05-2016', 6, 'C')
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName = ISNULL(@ColumnName + ', ','') + QUOTENAME(Header)
FROM (
SELECT t3.PoT + '_' + t3.Sts AS Header
FROM (
SELECT DISTINCT CONVERT(VARCHAR(3), DATENAME(M, t1.[Date])) + '-' + CONVERT(VARCHAR(2), DATENAME(Y, t1.[Date])) AS PoT, t2.Sts
FROM #tmp AS t1, (
SELECT DISTINCT Sts AS Sts
FROM #tmp
) AS t2
) AS t3
) AS combined
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX) = N''
SET @DynamicPivotQuery = N' SELECT Loc, ' + @ColumnName + '
FROM (
SELECT Loc, CONVERT(VARCHAR(3), DATENAME(M, [Date])) + ''-'' + CONVERT(VARCHAR(2), DATENAME(Y, [Date])) + ''_'' + Sts AS PoT, 1 AS ToT
FROM #tmp
) AS DT
PIVOT(SUM(ToT) FOR PoT IN (' + @ColumnName + ')) AS PT'
EXECUTE SP_EXECUTESQL @DynamicPivotQuery
DROP TABLE #tmp
Result:
Loc Jan-15_A Jan-15_B Jan-15_C Jan-16_A Jan-16_B Jan-16_C Mar-75_A Mar-75_B Mar-75_C May-13_A May-13_B May-13_C
Hyd 1 NULL NULL NULL NULL NULL 2 NULL NULL NULL NULL NULL
Viz NULL NULL 1 NULL NULL NULL NULL NULL 1 NULL NULL 1
Vjd NULL NULL NULL NULL 1 NULL NULL 1 NULL NULL 1 NULL