Сводный порядок SQL-сервера - PullRequest
0 голосов
/ 11 марта 2019

У меня есть следующая таблица

|rut  |fecha      |monto   |tipo
----------------------------------------
|123  |01/02/2018 | 125000 | SMS
|123  |01/05/2014 |  32500 | FOLLETO
|123  |01/04/2015 | 255000 | IA
|123  |01/02/2015 | 132850 | FOLLETO
|127  |01/07/2016 |  75000 | LIQUIDACION
|123  |01/08/2018 |  55000 | SMS
|123  |01/05/2018 | 180000 | SMS
|123  |01/12/2017 | 700000 | FOLLETO
|123  |01/11/2016 | 653200 | SMS
|784  |01/03/2015 |  88000 | FOLLETO
|123  |01/10/2017 |  60500 | SMS

У меня есть следующая таблица.

Эта таблица намного больше, но это помогает с примером, что мне нужно сделать дляопределенная колея, получи "monto" от "tipo".

И мне нужно получить что-то вроде этого

---------------------------------------------------------------------------
| rut: 123                                                                |
---------------------------------------------------------------------------
| tipo: SMS                                                               |
---------------------------------------------------------------------------
|year |jan |feb   |mar |apr |may   |jun |jul |aug  |sep |oct  |nov   |dec |
---------------------------------------------------------------------------
|2014 |null|nul   |null|null|null  |null|null|null |null|null |null  |null|
|2015 |null|null  |null|null|null  |null|null|null |null|null |null  |null|
|2016 |null|null  |null|null|null  |null|null|null |null|null |653200|null|
|2017 |null|null  |null|null|null  |null|null|null |null|60500|null  |null|
|2018 |null|125000|null|null|180000|null|null|55000|null|null |null  |null|
---------------------------------------------------------------------------
| tipo: FOLLETO                                                           |
---------------------------------------------------------------------------
|year |jan |feb   |mar |apr |may  |jun |jul |aug  |sep |oct  |nov   |dec |
---------------------------------------------------------------------------
|2014 |null|nul   |null|null|32500|null|null|null |null|null |null  |null|
|2015 |null|132850|null|null|null |null|null|null |null|null |null  |null|
|2016 |null|null  |null|null|null |null|null|null |null|null |null  |null|
|2017 |null|null  |null|null|null |null|null|null |null|null |null  |7000000|
|2018 |null|null  |null|null|null |null|null|null |null|null |null  |null|

1 Ответ

1 голос
/ 11 марта 2019

Пример данных

IF OBJECT_ID('tempdb..#TempTab')IS NOT NULL
DROP TABLE #TempTab
;WITH CTE_Temp (rut  ,fecha      ,monto   ,tipo)
AS
(
SELECT 123  ,'01/02/2018' , 125000 , 'SMS'          UNION ALL
SELECT 123  ,'01/05/2014' ,  32500 , 'FOLLETO'      UNION ALL
SELECT 123  ,'01/04/2015' , 255000 , 'IA'           UNION ALL
SELECT 123  ,'01/02/2015' , 132850 , 'FOLLETO'      UNION ALL
SELECT 127  ,'01/07/2016' ,  75000 , 'LIQUIDACION'  UNION ALL
SELECT 123  ,'01/08/2018' ,  55000 , 'SMS'          UNION ALL
SELECT 123  ,'01/05/2018' , 180000 , 'SMS'          UNION ALL
SELECT 123  ,'01/12/2017' , 700000 , 'FOLLETO'      UNION ALL
SELECT 123  ,'01/11/2016' , 653200 , 'SMS'          UNION ALL
SELECT 784  ,'01/03/2015' ,  88000 , 'FOLLETO'      UNION ALL
SELECT 123  ,'01/10/2017' ,  60500 , 'SMS'
)
SELECT * INTO #TempTab
FROM
(
SELECT *,
    DATENAME(MONTH,CONVERT(DATE,fecha,103)) MyMonths    
FROM CTE_Temp
)dt 

При использовании Dynamic sql

DECLARE @Column nvarchar(1000),@Column2 nvarchar(max),
        @Sql nvarchar(max)

SELECT @Column =STUFF((SELECT ', '+QUOTENAME(MonthName)
FROM
(
    SELECT   DATENAME(MONTH, DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthName], 
           MONTH(DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthNumber] 
    FROM master.dbo.spt_values s 
    WHERE [type] = 'P' AND s.number BETWEEN 0 AND 11
)dt 
 FOR XML PATH ('')),1,1,'')

SELECT @Column2 = STUFF((SELECT ', '+'MAX('+QUOTENAME(MonthName) +') AS '+QUOTENAME(MonthName)
FROM
(
    SELECT   DATENAME(MONTH, DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthName], 
           MONTH(DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthNumber] 
    FROM master.dbo.spt_values s 
    WHERE [type] = 'P' AND s.number BETWEEN 0 AND 11
)dt 
FOR XML PATH ('')),1,1,'')

SELECT @Sql = 'SELECT  DATEPART(YEAR,fecha) AS [Year],
                        MAX(rut) AS [Rut],
                        MAX(tipo) AS tipo,'+@Column2 +' 
                FROM 
                    (
                    SELECT * FROM #TempTab 
                    ) AS SRc
                PIVOT
                    (
                    MAX(monto) FOR MyMonths IN ('+@Column+')
                    ) AS pvt
                GROUP BY  DATEPART(YEAR,fecha)
                ORDER BY [Year]
                '


PRINT @Sql
EXEC (@Sql)

Результат

Year    Rut tipo    January  February   March   April   May     June    July    August  September   October November    December
---------------------------------------------------------------------------------------------------------------------------------
2014    123 FOLLETO NULL     NULL       NULL    NULL    32500   NULL    NULL    NULL    NULL        NULL     NULL        NULL
2015    784 IA      NULL     132850     88000   255000  NULL    NULL    NULL    NULL    NULL        NULL     NULL        NULL
2016    127 SMS     NULL     NULL       NULL    NULL    NULL    NULL    75000   NULL    NULL        NULL     653200      NULL
2017    123 SMS     NULL     NULL       NULL    NULL    NULL    NULL    NULL    NULL    NULL        60500    NULL        700000
2018    123 SMS     NULL     125000     NULL    NULL    180000  NULL    NULL    55000   NULL        NULL     NULL        NULL
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...