1

I understand that there is this command called PIVOT and that's what I probably need but first time trying to use it, seems like I can't get its syntax to work.

So here is my sample data:

CREATE TABLE MyTable 
(
    CompanyName NVARCHAR(20),
    Price INT,
    Project NVARCHAR(50)
);

INSERT INTO dbo.MyTable (CompanyName, Price, Project)
VALUES ('Dell', 450, 'Cleaning'),
       ('Dell', 150, 'Vaccuming'),
       ('Dell', 1200, 'Painting'),
       ('Dell', 100, 'VendingMachines'),
       ('Dell', 600, 'Wallpapers'),
       ('Dell', 820, 'Carpeting')

I want those Project Name turn into columns so for example having columns like "Cleaning" , "Carpeting" , etc and then value of each column is the Price.

This is what I tried so far but it is wrong syntax:

SELECT *
FROM
    (SELECT CompanyName, Price, Project
     FROM dbo.MyTable) src
PIVOT
    (SUM(Price)
        FOR Project IN ('Cleaning', 'Vaccuming', 'Painting', 'VendingMachines', 'Wallpapers', 'Carpeting')
    ) piv;

1 Answer 1

1

Bracket [] your column names

Example or dbFiddle

SELECT *
FROM
(
  SELECT  CompanyName, Price, Project
  FROM dbo.MyTable
) src
PIVOT
(
  SUM(Price)
  FOR Project IN ([Cleaning], [Vaccuming], [Painting], [VendingMachines], [Wallpapers], [Carpeting])
) piv;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.