October 21, 2016 at 8:25 pm
hi,
I want T-SQL query for getting output in Matrix format like below table view.I am using MS-Access as Database.
INPUT TABLE
NAME,SALARY,DATE
SAM-1,$67,21-10-2016
SAM-2,$34,21-10-2016
SAM-1,$39,20-10-2016
SAM-2,$45,20-10-2016
REQUIRED OUTPUT LIKE
NAME,21-10-2016,20-10-2016
SAM-1,$67,$39
SAM-2,$34,$45
THANK YOU
October 21, 2016 at 9:01 pm
DECLARE @yourTable TABLE(Name varchar(100), Salary money, dt date);
INSERT @yourTable VALUES
('SAM-1',$67,'20161021'),
('SAM-2',$34,'20161021'),
('SAM-1',$39,'20161020'),
('SAM-2',$45,'20161020');
SELECT
Name,
[21-10-2016] = SUM(CASE dt WHEN '20161021' THEN Salary END),
[20-10-2016] = SUM(CASE dt WHEN '20161020' THEN Salary END)
FROM @yourTable
GROUP BY Name;
-- Itzik Ben-Gan 2001
October 21, 2016 at 9:33 pm
To explain the ancient but very effective CROSS TAB method that Alan used, please see the following article, which comes complete with a performance test that demonstrates one of the many reasons why I think it's superior to the PIVOT operator.
[font="Arial Black"]Cross Tabs and Pivots, Part 1 – Converting Rows to Columns[/font][/url]
For an easy method to make it more dynamic and parameter flexible, please see the following article.
[font="Arial Black"]Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs[/font][/url]
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply