在SQL Server中使用Pivot将行转换为列

时间:2017-11-19 10:46:57

标签: sql-server

我有以下数据表:

date            Plant          Weight
2017-11-11  Gent        26
2017-11-11  Ang         25
2017-11-11  Ger         24
2017-11-11  ISS         23
2017-11-10  Gent        26
2017-11-10  Ang         25
2017-11-11  Ger         24
2017-11-11  ISS         23
2017-11-11  Gent        12
2017-11-11  Ang         13
2017-11-10  Gent        100

我希望它能作为数据透视表出现,如下所示:

datum           Ang Gent  Ger  ISS
2017-11-10      25  126   0    0
2017-11-11      38   38  48   46

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT *
FROM myTable
PIVOT
(
   MAX(Weight) FOR [Plant] IN ([Ang], [Gent], [Ger], [ISS])
) PVT;

答案 1 :(得分:0)

首先,如果您不想使用case运算符,则可以使用条件Pivot表达式条件

SELECT DATE [datum],
          SUM(CASE(PLANT) WHEN 'Ang' THEN Weight ELSE NULL END) [Ang],
          SUM(CASE(PLANT) WHEN 'Gent' THEN Weight ELSE NULL END) [Gent],
          SUM(CASE(PLANT) WHEN 'Ger' THEN Weight ELSE 0 END) [Ger],
          SUM(CASE(PLANT) WHEN 'ISS' THEN Weight ELSE 0 END) [ISS]
FROM <table> GROUP BY [DATE]

如果您对条件pivot表达式不满意,则另一个是动态case方式

DECLARE @Col NVARCHAR(MAX)
DECLARE @Query NVARCHAR(MAX)

SET @Col = STUFF((SELECT DISTINCT ','+QUOTENAME(PLANT) FROM <table> FOR XML PATH('')),1,1, '')

SET @Query = N'SELECT * FROM <table> 
                    PIVOT
                    (
                       sum(Weight) FOR [Plant] IN ('+@Col+')
                    ) PVT'

execute sp_executesql @Query

结果:

datum           Ang Gent  Ger  ISS
2017-11-10      25  126   0    0
2017-11-11      38   38  48   46

答案 2 :(得分:0)

let finalStr = ''
let str = 'Your a/c no. XXXXXXXXXX85 is credited on 15-11-17.'

let dateReg = /((?=\d{4})\d{4}|(?=[a-zA-Z]{3})[a-zA-Z]{3}|\d{2})((?=\/)\/|-)((?=[0-9]{2})[0-9]{2}|(?=[0-9]{1,2})[0-9]{1,2}|[a-zA-Z]{3})((?=\/)\/|-)((?=[0-9]{4})[0-9]{4}|(?=[0-9]{2})[0-9]{2}|[a-zA-Z]{3})/

const date = dateReg.exec(str)
finalStr = str.replace(date[0], `
 <div class="md-chip md-chip-clickable">
  <div class="md-chip-icon primary"><i class="material-icons">date_range</i></div>
   ${date[0]}
 </div>
`)

查询下方的行和列中的总数

select [datum],[Gent],[Ang],[ISS],[Ger],[Gent]+[Angouleme]+[ISS]+[Gerona] as [TOTAAL] FROM (select plant,datum,sum(weight) as weight FROM [MEPDARPD].[dbo].[Table1]  group by plant,datum)t
PIVOT
(
sum(Weight) 
FOR [Plant] IN ([Gent],[Ang],[ISS],[Ger])
) AS p

该查询解决了我的问题。谢谢你的帮助。