什么是将数据从单个表转换为此特定格式的T-SQl语法?

时间:2016-12-15 09:55:54

标签: sql sql-server tsql syntax unpivot

我正在使用SQL Server 2014,我的数据库中有一个名为MyTable的表。提取物如下所示:

protected

我需要转换此表,以便我的SQL查询输出如下:

Hotel   Market    Desc    Jan16      Feb16       
ABC     France    SUP HB   158        33       
ABC     France    SUP AI    35         6       
ABC     France    DLX HB    27        10       

如何使用T-SQL实现此输出?在阅读了有关网络问题的一些内容之后,我相信UNPIVOT语法可能会起作用,但我完全不知道如何在此上下文中使用它。

3 个答案:

答案 0 :(得分:1)

select  Hotel  ,  Market,[desc],marks,Date 
from #c s
unpivot
(
  marks
  for date in (jan16, feb16)
) u;

或 2)

SELECT  HOTEL ,MARKET,A.[DESC] MARKET,[DATE] ,V.[DESC]
FROM   #C A
       CROSS APPLY (VALUES('JAN16', JAN16),
                          ('FEB16', FEB16))
                       V   (DATE, [DESC]); 
output

Hotel   Market  desc    marks   Date
ABC France  SUP HB  158 Jan16
ABC France  SUP HB  33  Feb16
ABC France  SUP AI  35  Jan16
ABC France  SUP AI  6   Feb16
ABC France  DLX HB  27  Jan16
ABC France  DLX HB  10  Feb16

答案 1 :(得分:0)

一种简单的方法是使用UNION

SELECT Hotel, Market, Desc, 'Jan16' AS Date, Jan16 AS Values
FROM MyTable
UNION ALL
SELECT Hotel, Market, Desc, 'Feb16', Feb16
FROM MyTable

如果你期望比这更复杂的东西,例如超过两列,然后您可以尝试使用UNPIVOT

答案 2 :(得分:0)

select  *
from    mytable unpivot ("values" for "date" in (Jan16,Feb16)) u
+-------+--------+--------+--------+-------+
| Hotel | Market | Desc   | values | date  |
+-------+--------+--------+--------+-------+
| ABC   | France | SUP HB | 158    | Jan16 |
+-------+--------+--------+--------+-------+
| ABC   | France | SUP HB | 33     | Feb16 |
+-------+--------+--------+--------+-------+
| ABC   | France | SUP AI | 35     | Jan16 |
+-------+--------+--------+--------+-------+
| ABC   | France | SUP AI | 6      | Feb16 |
+-------+--------+--------+--------+-------+
| ABC   | France | DLX HB | 27     | Jan16 |
+-------+--------+--------+--------+-------+
| ABC   | France | DLX HB | 10     | Feb16 |
+-------+--------+--------+--------+-------+