我有类似下面的数据。
VariableName variableValue
row_count 5326
FileName [OrderFeed_20160406.tsv]
TableName OrderFeed
TableID 1
row_count 788
FileName [CategoryFeed_20160406.tsv]
TableName Category
TableID 2
row_count 224
FileName [ItemFeed_20160406.tsv]
TableName Item
TableID 3
row_count 991
FileName [ContactFeed_20160406.tsv]
TableName Contact
TableID 4
我希望显示如下数据:
row_count | FileName | TableName |TableID
5326 |[OrderFeed_20160406.tsv] |OrderFeed |1
788 |[CategoryFeed_20160406.tsv]|Category |2
当我使用PIVOT时,它是工作但数据的顺序正在改变。我的意思是,如果[OrderFeed_20160406.tsv]有5326行,并且它的TableId实际为1但是在枢轴[OrderFeed_20160406.tsv]之后有788行并获得不同的TableID als。
我的示例透视代码如下:
select row_count,
[FileName],
TableID,
TableName from (
select VariableName , VariableValue,row_number() over(partition by VariableName
order by VariableValue) seq
from DailyLogs
) d
PIVOT (count(VariableValue) for variableName in ( row_count,
FileName,
TableID,
TableName))
piv;
答案 0 :(得分:0)
试试这个
DECLARE @TABLE TABLE (row_no INT IDENTITY(1,1), variableName NVARCHAR(200)
,variableValue NVARCHAR(200))
INSERT INTO @TABLE
SELECT * FROM DailyLogs
SELECT [row_count],[FileName],[TableName],[TableID]
FROM (
SELECT variableName,variableValue,
ROW_NUMBER() OVER(PARTITION BY variableName ORDER BY row_no) AS ROWNO FROM @TABLE
) T PIVOT( MAX(VariableValue) FOR
variableName IN ([FileName],[row_count],[TableID],[TableName])) PIV
ORDER BY [TableID]
Result is :
row_count FileName TableName TableID
5326 [OrderFeed_20160406.tsv] OrderFeed 1
788 [CategoryFeed_20160406.tsv] Category 2
224 [ItemFeed_20160406.tsv] Item 3
991 [ContactFeed_20160406.tsv] Contact 4