将值转换为列名称

时间:2016-10-03 08:30:41

标签: sql sql-server pivot

我有一个包含以下行的表:

Sr.  Name         Product    Qty
1    Yogesh       ALB         1
2    Suresh       AMS         2
3    Yogesh       ALB         2
4    Mahesh       MAS         5

现在,我想要显示以下样式的显示记录......

Sr.    Name      ALB  AMS  MAS
1      Yogesh     3    0    0
2      Suresh     0    2    0
3      Mahesh     5    0    0

3 个答案:

答案 0 :(得分:1)

BEGIN TRAN
CREATE TABLE #temp
(
  Sr Int NOT null,  Name  Varchar(255),  Product   Varchar(255) ,    Qty numeric
)

INSERT INTO #temp
SELECT 1 ,'Yogesh',  'ALB', 1 UNION All
Select 2  ,  'Suresh','AMS',2  UNION All
Select 3  ,  'Yogesh' , 'ALB',2  UNION All
Select 4 ,   'Mahesh','MAS',5

SELECT NAME,ISNULL(ALB,0) AS ALB,ISNULL(AMS,0) AS AMS,ISNULL(MAS,0) AS MAS
FROM (
    SELECT 
        (Name) as Name,left(Product,3)as Product, 
        Isnull(Qty,0) as Qty 
    FROM #temp
) as s
PIVOT (SUM(QTY) FOR PRODUCT IN (ALB, AMS, MAS)) AS pvt
ORDER BY Name

ROLLBACK TRAN

答案 1 :(得分:1)

尝试使用以下查询。

SELECT ROW_NUMBER()OVER(ORDER BY (SELECT 1)) [Sr.],Name,ISNULL(ALB,0) AS ALB,ISNULL(AMS,0) AS AMS,ISNULL(MAS,0) AS MAS
FROM (
    SELECT Name,Product, 
        ISNULL(Qty,0) as Qty 
    FROM #temp
) as s
PIVOT (SUM(QTY) FOR PRODUCT IN (ALB, AMS, MAS)) AS pvt

答案 2 :(得分:0)

使用

SELECT NAME,ISNULL(ALB,0) AS ALB,ISNULL(AMS,0) AS AMS,ISNULL(MAS,0) AS MAS
FROM
(SELECT  NAME,PRODUCT,SUM(QTY) QTY FROM TABLENAME
GROUP BY NAME,PRODUCT) A
PIVOT(SUM(QTY) FOR PRODUCT IN (ALB,AMS,MAS)) AS PVT