3

我有一个表格,其中一行数据:

Account | OrderID   | OrderName          | Priority | Fasting   |AssignedTo       |ResultsTo    |Location
----------------------------------------------------------------------------------------------------------------------------
12345   | REQ123456 | Lipid Panel (1.2)  |Routine   | Yes       |Fast, Brook      |Nurse Group  |Fisher Rd, Woodbridge, NV

现在我想 UNPIVOT 数据以以下形式显示用户:

GROUPCOL    | LABEL       | VALUE
-------------------------------------------------
General     | Account     | 12345
General     | OrderID     | REQ123456
General     | OrderName   | Lipid Panel (1.2)
General     | Priority    | Routine    
General     | Fasting     | Yes        
Result      | ResultsTo   | Nurse Group
Result      | AssignedTo  | Fast, Brook
Result      | Location    | Fisher Rd, Woodbridge, NV

我正在努力寻找限制 UNPIVOT 默认对列进行排序的解决方案。我想按我的方式订购这些列。这是查询:

SELECT  'General' GROUPCOL, LABEL, VALUE
FROM TESTPIVOT
UNPIVOT (
    VALUE FOR LABEL IN (Account, OrderID, OrderName, Priority, Fasting)
) AS UNPVT
UNION
SELECT  'Result' GROUPCOL, LABEL, VALUE
FROM TESTPIVOT
UNPIVOT (
    VALUE FOR LABEL IN (AssignedTo, ResultsTo, Location)
) AS UNPVT

输出是:

GROUPCOL    | LABEL       | VALUE
-------------------------------------------------
General     | Account     | 12345
General     | Fasting     | Yes        
General     | OrderID     | REQ123456
General     | OrderName   | Lipid Panel (1.2)
General     | Priority    | Routine    
Result      | AssignedTo  | Fast, Brook
Result      | Location    | Fisher Rd, Woodbridge, NV 
Result      | ResultsTo   | Nurse Group

我想,如果我有一个与列关联的订单列,那么我可以根据需要在最后订购它(这样,我可以根据要求更改订单)。

4

1 回答 1

6

既然您使用的是 SQL Server 2008,那么您可以使用CROSS APPLYVALUES来 UNPIVOT 数据。使用这将允许您为排序顺序创建一个列:

select c.GroupCol, c.Label, c.Value
from testpivot
cross apply
(
  values
  ('General', 'Account', Account, 1),
  ('General', 'OrderID', OrderID, 2),
  ('General', 'OrderName', OrderName, 3),
  ('General', 'Priority', Priority, 4),
  ('General', 'Fasting', Fasting, 5),
  ('Result', 'ResultsTo', ResultsTo, 6),
  ('Result', 'AssignedTo', AssignedTo, 7),
  ('Result', 'Location', Location, 8)
) c (GroupCol, Label, Value, SortOrder)
order by sortorder;

请参阅带有演示的 SQL Fiddle

于 2013-06-18T18:30:53.113 回答