在SQL Server中使用groupby进行子选择不起作用

时间:2018-10-15 19:33:24

标签: sql sql-server tsql

这是我的选择

SELECT
    (FORMAT(DOC.DATAEMISSAO, 'MM','PT-BR')) + '-' + (FORMAT(DOC.DATAEMISSAO, 'yyyy','PT-BR')) AS 'year/mouth',
    ROUND(SUM(ITEM.VALORLIQUIDO),2) AS 'value'
FROM 
    FN_DOCUMENTOS DOC,
    CM_OPERACOESFATURAMENTO OFAT,
    CM_ITENS ITEM,
    PD_PRODUTOS PF
WHERE
    (OFAT.HANDLE = DOC.OPERACAOFATURAMENTO)
    AND (ITEM.DOCUMENTO = DOC.HANDLE)
    AND (PF.HANDLE = ITEM.PRODUTO)
    AND (OFAT.CODIGO IN (101,102,103,104,106,120,125,145,147,
     148,150,151,153,163,164,170,171,180,182,184,185,186,
     201,202,203,220,225,245,248,249,250,251,253,263,264,
     280,282,301,302,304,319,320,345,347,351,353,363,364,
     365,371,380,385)) 
    AND (DOC.FILIAL IN (1))
    AND (PF.MARCAPRODUTO IN (1,5))
    AND (DOC.DATAEMISSAO >= DATEADD(MONTH, -11, GETDATE()))
GROUP BY FORMAT(DOC.DATAEMISSAO, 'yyyy','PT-BR'),FORMAT(DOC.DATAEMISSAO, 'MM','PT-BR')
ORDER BY  FORMAT(DOC.DATAEMISSAO, 'yyyy','PT-BR'), FORMAT(DOC.DATAEMISSAO, 'MM','PT-BR')

这是我的品牌“ 1”和“ 5”的结果

 month - year  |    value
    11-2017        7793.85
    12-2017        90862.51
    01-2018        681044.4
    02-2018        862552.22
    03-2018        963484.25
    04-2018        1127765.61
    05-2018        1485678.23
    06-2018        1249055.52
    07-2018        2098446.61
    08-2018        1765752.61
    09-2018        1139268.88
    10-2018        679253.04

我需要它的第3列,其他品牌(2、3、4)的价值。

我无法创建子选择,因为从视图到“分组依据”时出现错误。

2 个答案:

答案 0 :(得分:1)

您可以使用所有必需的数据,并使用条件聚合将其分为两列:

%20

答案 1 :(得分:0)

在您的选择中-更改分组依据

发件人:

GROUP BY FORMAT(DOC.DATAEMISSAO, 'yyyy','PT-BR'),FORMAT(DOC.DATAEMISSAO, 'MM','PT-BR')

收件人:

GROUP BY  (FORMAT(DOC.DATAEMISSAO, 'MM','PT-BR')) + '-' + (FORMAT(DOC.DATAEMISSAO, 'yyyy','PT-BR'))