使用UNPIVOT时格式化列

时间:2015-08-08 09:12:55

标签: sql-server tsql unpivot

我有一个包含以下结构的表

YEAR, MONTH, ITEM, REQ_1,REQ_2,REQ_3,,.....REQ_31
2015,   07,  AAA,   100,   200, 300.......550

我想将它们取消格式化

ITEM,  Date, Quantity
AAA,01-07-2015,100
AAA,02-07-2015,200
AAA,03-07-2015,300
.
.
AAA,31-07-2015,550

我可以使用UNPIVOT使用以下语句获取数据

SELECT C.ITEM, CONVERT(DATETIME, (C.YEAR + C.MONTH + SUBSTRING(C.REQUIRED_DAY,8,2)),112) AS REQ_DATE,C.QUANTITY FROM 
(SELECT B.YEAR, B.MONTH, B.ITEM, B.REQUIRED_DAY, B.QUANTITY
FROM C25KPPF A
UNPIVOT
(   
    QUANTITY FOR REQUIRED_DAY IN ([REQ_QTY1], [REQ_QTY2], [REQ_QTY3]....[REQ_QTY31])
) AS B 
WHERE B.QUANTITY <> 0)  C

事情是 - 我想避免在这里使用嵌套选择 - 一个选择为unpivot,另一个选择将其格式化为文本的日期时间。

有没有办法在一个单独的select语句中将它们合并在一起?

2 个答案:

答案 0 :(得分:1)

尝试以下查询:

SELECT  up.*, 
        DATEFROMPARTS(up.[YEAR], up.[MONTH], up.[DAY]) AS SaleDate, -- SQL2012+
        DATEADD(DAY, up.[DAY] - 1, DATEADD(MONTH, up.[MONTH] - 1, DATEADD(YEAR, up.[YEAR]-1900, {d '1900-01-01'}))) AS SaleDate2, -- SQL2005+
        CONVERT(SMALLDATETIME, LTRIM(up.[YEAR]) + RIGHT('0' + LTRIM(up.[MONTH]), 2) + RIGHT('0' + LTRIM(up.[DAY]), 2)) AS SalesDate3 -- SQL2005+
FROM (VALUES 
    (2015, 7, 'AAA', 100, 200, 300, 400),
    (2015, 8, 'BBB', 500, NULL, NULL, NULL)
) ms([YEAR], [MONTH], ITEM, REQ_1,REQ_2,REQ_3,REQ_4) -- MonthlySales
CROSS APPLY (
                                                        -- Remove WHERE filters to get all days (including those without sales)
    SELECT ms.ITEM, ms.[YEAR], ms.[MONTH], 1, ms.REQ_1 WHERE ms.REQ_1 IS NOT NULL 
    UNION ALL 
    SELECT ms.ITEM, ms.[YEAR], ms.[MONTH], 2, ms.REQ_2 WHERE ms.REQ_2 IS NOT NULL 
    UNION ALL 
    SELECT ms.ITEM, ms.[YEAR], ms.[MONTH], 3, ms.REQ_3 WHERE ms.REQ_3 IS NOT NULL 
    UNION ALL 
    SELECT ms.ITEM, ms.[YEAR], ms.[MONTH], 4, ms.REQ_4 WHERE ms.REQ_4 IS NOT NULL 
    -- UNION ALL ... other months
) up(ITEM, [YEAR], [MONTH], [DAY], REQ) -- Unpivot

输出:

/*
ITEM YEAR        MONTH       DAY         REQ         SaleDate   SaleDate2  SalesDate3
---- ----------- ----------- ----------- ----------- ---------- ---------- ----------
AAA  2015        7           1           100         2015-07-01 2015-07-01 2015-07-01
AAA  2015        7           2           200         2015-07-02 2015-07-02 2015-07-02
AAA  2015        7           3           300         2015-07-03 2015-07-03 2015-07-03
AAA  2015        7           4           400         2015-07-04 2015-07-04 2015-07-04
BBB  2015        8           1           500         2015-08-01 2015-08-01 2015-08-01
*/

答案 1 :(得分:0)

没关系 - 想通了。我喝的是什么,我没有立刻看到这个? ....DATETIMEFROMPARTS(C.YEAR,C.MONTH, SUBSTRING(C.REQUIRED_DATE,8,2),0,0,0,0)...... –