简体   繁体   English

在 T-SQL 中将多行转换为具有多列的一行

[英]Convert multiple rows into one row with multiple columns in T-SQL

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.我知道有一个名为PIVOT命令,这就是我可能需要的,但第一次尝试使用它时,似乎我无法使用它的语法。

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 .我希望这些Project Name变成列,例如有像 "Cleaning" 、 "Carpeting" 等的列,然后每列的值是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;

Bracket [] your column names括号[]你的列名

Example or dbFiddle示例或dbFiddle

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM