温馨提示:本文翻译自stackoverflow.com,查看原文请点击:tsql - Pivot this different way

tsql - 以不同的方式旋转

发布于 2020-03-27 15:51:45

我想知道是否可以用不同的方式来解决这个问题,现在这就是我得到的:

SELECT [1] as semana1, [2] as semana2, [3] as semana3, [4] as semana4, [5] as semana5 , [BZ/TDZ]
FROM (


SELECT        { fn WEEK(SCHEMA.SORDERQ.ORDDAT_0) } AS Semana, SCHEMA.ITMMASTER.TSICOD_3 as 'BZ/TDZ', SUM(SCHEMA.SORDERQ.QTY_0 * (SCHEMA.SORDERP.NETPRINOT_0 * SCHEMA.SORDER.CHGRAT_0)) 
                         AS [Total A.I]
FROM            SCHEMA.SORDERQ INNER JOIN
                         SCHEMA.SORDER ON SCHEMA.SORDERQ.SOHNUM_0 = SCHEMA.SORDER.SOHNUM_0 INNER JOIN
                         SCHEMA.ITMMASTER ON SCHEMA.SORDERQ.ITMREF_0 = SCHEMA.ITMMASTER.ITMREF_0 RIGHT OUTER JOIN
                         SCHEMA.SORDERP ON SCHEMA.SORDERQ.SOPLIN_0 = SCHEMA.SORDERP.SOPLIN_0 AND SCHEMA.SORDER.SOHNUM_0 = SCHEMA.SORDERP.SOHNUM_0
WHERE        (SCHEMA.SORDERQ.CPY_0 = N'BZES') AND (YEAR(SCHEMA.SORDERQ.ORDDAT_0) = YEAR(GETDATE()))
GROUP BY SCHEMA.ITMMASTER.TSICOD_3, { fn WEEK(SCHEMA.SORDERQ.ORDDAT_0) }) as DT

PIVOT (sum([Total A.I]) FOR Semana IN ([1], [2], [3], [4], [5]))
as PT

哪个返回

输出量

这是我得到的输出,其中“ Semana1”表示Week1

可以某种方式命令它得到这样的东西:

          BZ        TDZ

Week1    93150.94   425902.09
Week2
Week3

这主要是因为我按周订购,一年中有很多周。我的输出方式非常大(水平)

谢谢 !

查看更多

查看更多

提问者
Antonio
被浏览
16
Søren Kongstad 2020-01-31 16:24

您基本上是在内部选择中执行此操作。

我整理了一下,然后将总和分为2个不同的总和,一个用于BZ,一个用于TDZ

而且不要使用{fn week(...}

datepart(week,SCHEMA.SORDERQ.ORDDAT_0) 

或者如果您在欧盟使用

datepart(ISO_WEEK,SCHEMA.SORDERQ.ORDDAT_0) 

这是完整的查询

SELECT
    'Semana' + Right('0'+STR(DATEPART(WEEK, [SCHEMA].SORDERQ.ORDDAT_0)),2) AS Semana
   ,SUM(IIF([SCHEMA].ITMMASTER.TSICOD_3 = 'BZ'
    , [SCHEMA].SORDERQ.QTY_0 * [SCHEMA].SORDERP.NETPRINOT_0 * [SCHEMA].SORDER.CHGRAT_0, 0)
    ) BZ
   ,SUM(IIF([SCHEMA].ITMMASTER.TSICOD_3 = 'TDZ'
    , [SCHEMA].SORDERQ.QTY_0 * [SCHEMA].SORDERP.NETPRINOT_0 * [SCHEMA].SORDER.CHGRAT_0, 0)
    ) TDZ
FROM [SCHEMA].SORDERQ
INNER JOIN [SCHEMA].SORDER
    ON [SCHEMA].SORDERQ.SOHNUM_0 = [SCHEMA].SORDER.SOHNUM_0
INNER JOIN [SCHEMA].ITMMASTER
    ON [SCHEMA].SORDERQ.ITMREF_0 = [SCHEMA].ITMMASTER.ITMREF_0
RIGHT OUTER JOIN [SCHEMA].SORDERP
    ON [SCHEMA].SORDERQ.SOPLIN_0 = [SCHEMA].SORDERP.SOPLIN_0
        AND [SCHEMA].SORDER.SOHNUM_0 = [SCHEMA].SORDERP.SOHNUM_0
WHERE ([SCHEMA].SORDERQ.CPY_0 = N'BZES')
AND (YEAR([SCHEMA].SORDERQ.ORDDAT_0) = YEAR(GETDATE()))
GROUP BY 'Semana' + Right('0'+STR(DATEPART(WEEK, [SCHEMA].SORDERQ.ORDDAT_0)),2)

发布
问题

分享
好友

手机
浏览

扫码手机浏览