从SQL转出输出

时间:2016-02-23 09:05:33

标签: sql sql-server pivot

假设我有一张桌子销售

通过这个选择,我得到了这个。

SELECT CustID, Date, ArtikelNr FROM Sales

CustID  Date         ArtikelNr
1       23.02.2016   50
1       14.02.2016   40
2       22.02.2016   40
1       24.02.2016   50

现在我想要像这样的输出。

CustID  ArtikelNr Date1        Date2       Date3  ... DateN
1       50        23.02.2016   24.02.2016
1       40        14.02.2016
2       50        24.02.2016

我该怎么做?

1 个答案:

答案 0 :(得分:4)

我认为您的输入数据或示例输出可能存在问题,因为您的上一个输出行似乎与您的任何输入都不匹配。

我认为您正在寻求动态支点,如下所示:

测试数据

SET DATEFORMAT DMY
CREATE TABLE #Test (CustId INT, Date DATE, ArtikelNr INT)
INSERT INTO #Test VALUES
(1,'23.02.2016',50),
(1,'14.02.2016',40),
(2,'22.02.2016',40),
(1,'24.02.2016',50)

查询

DECLARE @Query AS NVARCHAR(MAX)
DECLARE @Cols AS NVARCHAR(MAX)
SELECT @Cols= ISNULL(@Cols + ',','') + QUOTENAME(RN) FROM (SELECT DISTINCT ROW_NUMBER() OVER (PARTITION BY CustId, ArtikelNr ORDER BY CustId) RN FROM #Test) Z

SET @Query = 
  N'SELECT * FROM 
    (SELECT *, ROW_NUMBER() OVER (PARTITION BY CustId, ArtikelNr ORDER BY CustId) RN FROM #Test) A
    PIVOT ( MIN(DATE) FOR RN IN ('+@Cols+')) PVT
ORDER BY CustId, ArtikelNr DESC'

EXEC sp_executesql @Query

CustId      ArtikelNr   1          2
----------- ----------- ---------- ----------
1           50          2016-02-23 2016-02-24
1           40          2016-02-14 NULL
2           40          2016-02-22 NULL