SQL Vertical table to Horizontal table

Hello Experts Exchange
I have a table of data that I need to group by category, I have attached a Excel spreadsheet with two tables.

Table 1 is how I have the data, and I need the SQL Script to get table 2.

Regards

SQLSearcher
Sample-Data.xls
SQLSearcherAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brian CroweDatabase AdministratorCommented:
DECLARE @SampleData TABLE
(
	Sale_Date	DATE,
	Shop_Ref	INT,
	Category	VARCHAR(50),
	Price_Paid	MONEY
);

INSERT INTO @SampleData (Sale_Date, Shop_Ref, Category, Price_Paid)
VALUES
	('11/5/2015', 1, 'Cat1', 3	),
	('11/5/2015', 1, 'Cat1', 3	),
	('11/5/2015', 1, 'Cat1', 4	),
	('11/5/2015', 1, 'Cat2', 5	),
	('11/5/2015', 2, 'Cat2', 2	),
	('11/5/2015', 2, 'Cat3', 12	),
	('11/5/2015', 2, 'Cat3', 10	),
	('11/5/2015', 3, 'Cat1', 2	),
	('11/5/2015', 3, 'Cat1', 3	),
	('11/6/2015', 3, 'Cat1', 4	),
	('11/6/2015', 3, 'Cat1', 5	);

SELECT Sale_Date, Shop_Ref, ISNULL([Cat1], 0) AS Cat1, ISNULL([Cat2], 0) AS Cat2, ISNULL([Cat3], 0) AS Cat3
FROM
(
	SELECT *
	FROM @SampleData
) AS S
PIVOT
(
	SUM(Price_Paid)
	FOR Category IN ([Cat1], [Cat2], [Cat3])
) AS P

Open in new window

PortletPaulEE Topic AdvisorCommented:
There is another way of doing this (aside from using "pivot")

SELECT
      Sale_Date
    , Shop_Ref
    , ISNULL(SUM(CASE WHEN Category='Cat1' THEN [Price_Paid] END),0) AS Cat1
    , ISNULL(SUM(CASE WHEN Category='Cat2' THEN [Price_Paid] END),0) AS Cat2
    , ISNULL(SUM(CASE WHEN Category='Cat3' THEN [Price_Paid] END),0) AS Cat3
FROM SampleData
GROUP BY
      Sale_Date
    , Shop_Ref
;

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SQLSearcherAuthor Commented:
Thank you for your help.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.