如何透视表记录?

时间:2016-04-06 06:18:33

标签: sql sql-server pivot-table

如何分组记录并透视它们? 用于检索以下记录的SQL查询如下:

BarChart

enter image description here

希望输出格式为

enter image description here

提前致谢

2 个答案:

答案 0 :(得分:1)

给它一个这样的镜头...查询没有经过测试,如果失败让我知道所以我可以解决它......但这就是你想要的,你只需要支点

    select * from (
select d.Name as DrawerBox
 , dt.Name as DrawerBoxType
 , di.Inches as Inches
 , isnull(dbc.Value, dc.Value) Value      
from DrawerBox_C dc
    join DrawerBox d
        on d.DrawerBoxId = dc.DrawerBoxId
    join DrawerBoxInches  di
        on di.DrawerBoxInchesId = dc.DrawerBoxInchesId
    join DrawerBoxType dt
        on dt.DrawerBoxTypeId = dc.DrawerBoxTypeId
    left join dbo.DrawerBox_Bid_C dbc
        on dbc.DrawerBox_C_Id = dc.DrawerBox_C_Id
        and dbc.BidId = 1
) src
  PIVOT
  (
    Max(value) 
    for Inches in ([12], [18], [24], [30], [36])
  ) piv
order by DrawerBox, DrawerBoxType

答案 1 :(得分:-1)

您可以使用以下内容动态运行查询。这意味着即使你添加新的"英寸"值将自动为您创建它们。还提供了下面的手动插入,以便您可以进行测试。另请注意,这是抓住最大值"值"对于每个DrawerBox / DrawerBoxType。您还可以使用" Avg"," Min"," Sum"相反,如果你愿意。

Drop Table #PivotRecs
Create Table #PivotRecs (DrawerBox nvarchar(200), DrawerBoxType nvarchar(200), Inches int, Value int)
Insert Into #PivotRecs
select d.Name as DrawerBox
     , dt.Name as DrawerBoxType
     , di.Inches as Inches
     , isnull(dbc.Value, dc.Value) Value      
from DrawerBox_C dc
join DrawerBox d
  on d.DrawerBoxId = dc.DrawerBoxId
join DrawerBoxInches  di
  on di.DrawerBoxInchesId = dc.DrawerBoxInchesId
join DrawerBoxType dt
  on dt.DrawerBoxTypeId = dc.DrawerBoxTypeId
left join dbo.DrawerBox_Bid_C dbc
  on dbc.DrawerBox_C_Id = dc.DrawerBox_C_Id
  and dbc.BidId = 1


  --Insert Into #PivotRecs
  --Select 'Melamine', 'Standard', 12, 3 Union
  --Select 'Melamine', 'Standard', 18, 6 Union
  --Select 'Melamine', 'Standard', 24, 9 Union
  --Select 'Melamine', 'Standard', 30, 12 Union
  --Select 'Melamine', 'Standard', 36, 15 Union
  --Select 'Melamine', 'File', 12, 5 Union
  --Select 'Melamine', 'File', 18, 8 Union
  --Select 'Melamine', 'File', 24, 11 Union
  --Select 'Melamine', 'File', 30, 14 Union
  --Select 'Melamine', 'File', 36, 17 


Declare @Inch int, @SQL nvarchar(max),@Inchs nvarchar(max),@SQL2 nvarchar(max), @i int
Set @i = 0
Set @SQL = ''
Set @SQL2 = ''
Set @Inchs = ''
DECLARE iCursor CURSOR
LOCAL
FAST_FORWARD
FOR 
Select Distinct Inches From #PivotRecs  Order By Inches
  OPEN iCursor
FETCH NEXT FROM iCursor INTO @Inch
WHILE (@@fetch_status <> -1)
BEGIN
If(@i=1)
Begin
Set @SQL = @SQL + ',['+Cast(@Inch as nvarchar(4))+']'
Set @Inchs= @Inchs + ','+Cast(@Inch as nvarchar(4))+''
End
If(@i=0)
Begin
Set @SQL = @SQL + '['+Cast(@Inch as nvarchar(4))+']'
Set @Inchs = @Inchs + ''+Cast(@Inch as nvarchar(4))+''
Set @i = 1
End

FETCH NEXT FROM iCursor INTO @Inch
Continue
End 
Set @SQL2 = 
'Select * 
From
(Select Distinct DrawerBox, DrawerBoxType, Inches, Value From #PivotRecs) a
pivot (
   max (a.Value) 
   for Inches in ('+@SQL+'))   
   as Inches
   Order By 1'

Exec SP_ExecuteSQL @SQL2