如果问题重复,我道歉但我有一些要求让我感到紧张。经过多次尝试,我无法解决它。要求是我有一个表格,其数据如下:
CHANGE_NUMBER ITEM_NUMBER REV BOM_ITEM FIND_NUMBER QUANTITY
MD04086 710851-1 B 230248-0 0 9
MD04086 710851-1 B 230289-0 0 4
MD04086 710851-1 B 230292-0 0 1
MD04086 710851-1 B 230298-0 0 2
我想对这些数据做些什么是按照以下格式制作:
Column_name Column_Value
CHANGE_NUMBER MD04086
ITEM_NUMBER 710851-1
REV B
BOM_ITEM 230248-0
FIND_NUMBER 0
QUANTITY 9
CHANGE_NUMBER MD04086
ITEM_NUMBER 710851-1
REV B
BOM_ITEM 230289-0
FIND_NUMBER 0
QUANTITY 4
到目前为止,我使用了以下查询,但它没有提供我想要实现的内容
with q1 as
(select 'itemRev' as column_name,[CHANGE_NUMBER] as column_value from generalassemblies_data_final
union all
select 'itemNumber' as column_name,[ITEM_NUMBER] as column_value from generalassemblies_data_final
union all
select 'REV' as column_name,[REV] as column_value from generalassemblies_data_final
union all
select 'BOM_ITEM' as column_name,[BOM_ITEM] as column_value from generalassemblies_data_final
union all
select 'findNum' as column_name,[FIND_NUMBER] as column_value from generalassemblies_data_final
union all
select 'qty' as column_name,[QUANTITY] as column_value from generalassemblies_data_final
)
select *
from q1;
有人可以帮帮我吗。
答案 0 :(得分:2)
Select ColumnName
, ColumnValue
FROM
(
--<-- Make sure all the columns are converted to the same data type here
-- This is the only purpose of this sub-query
Select CHANGE_NUMBER
,ITEM_NUMBER
,REV
,BOM_ITEM
,CAST(FIND_NUMBER AS VARCHAR(100)) AS FIND_NUMBER
,CAST(QUANTITY AS VARCHAR(100)) AS QUANTITY
from TableName --<-- Your Table name here
)t
UNPIVOT (ColumnValue for ColumnName
IN (CHANGE_NUMBER , ITEM_NUMBER , REV
,BOM_ITEM , FIND_NUMBER , QUANTITY)
)UP
答案 1 :(得分:1)
如果column_values全部转换为相同的类型(nvarchar?),您的UNION ALL列表将会起作用。除此之外,我建议您查看表示级问题,该问题由可以使用查询结果的程序处理。
我认为任何报表设计师都可以工作。如果您希望在3GL等3GL中执行此操作,则只需保留基于行的查询并写出格式化数据:
for each row in someresult
Console.WriteLine(string.format("Change Number" & vbtab & "{0}", row.ChangeNumber)
Console.WriteLine(string.format("Item Number" & vbtab & "{0}", row.ItemNumber)
next
我无法在这里为您提供精确的语法,但结果,输出流和格式的混合可以起作用。
答案 2 :(得分:1)
您也可以使用APPLY
运算符执行此类操作:
select Transposed.*
from <TableName>
cross apply (values
(CHANGE_NUMBER)
, (ITEM_NUMBER)
, (REV)
, (BOM_ITEM)
, (FIND_NUMBER)
, (QUANTITY)
, (CHANGE_NUMBER)
, (ITEM_NUMBER)
, (REV)
, (BOM_ITEM)
, (Cast(FIND_NUMBER as varchar(10)))
, (Cast(QUANTITY as varchar(10)))
) as Transposed (ChangeNumber, ItemNumber, Revision, BomItem, FindNumber, Quantity);
我更喜欢这个版本,因为我已经在常规版本上使用APPLY
,发现它比UNPIVOT
更容易记住。另外,我只使用PascalCase对列进行别名以突出显示语法;随时将它们改为你想要的任何东西。