MSSQL 2005服务器SUM通过分组

时间:2016-01-05 11:52:14

标签: sql sql-server group-by sum

我有sql查询,它给我发票行的结果。

我得到了所有真实的信息,但我想将它分组。问题是我已经将它分组了。

有我的代码:

WITH Agg1 AS(
SELECT  [Ship-to Name] As 'Pirkejas',
        [Order No_]
FROM [Artilux].[dbo].[Trivilita UAB$Sales Invoice Header]
)

SELECT  sil.[Document No_] as 'Pardavimo nr.',
    sil.[Shipment Date] as 'Siuntos data',
    sil.[Order No_] as 'Musu užsak. nr.',
    sil.[Customer Order No_]  AS 'Klientio užsak. nr.',
    a.[Pirkejas],
    CAST(sil.[Unit Volume]*sil.[Quantity] AS DECIMAL(16,4)) AS 'Tūris',
    CAST(sil.[Unit Price]*sil.[Quantity] AS DECIMAL(16,2)) AS 'Suma €'

FROM [Artilux].[dbo].[Trivilita UAB$Sales Invoice Line] sil

LEFT JOIN Agg1 a
ON a.[Order No_] = sil.[Order No_]

WHERE sil.[Sell-to Customer No_] = 'PRK0820' 
AND sil.[Shipment Date] > '2015-09-01 00:00:00.000'
AND sil.[Shipment Date] <= dateadd(day,datediff(day,0,GETDATE()),0)  AND sil.[Document No_] = 'TRV0093219'
GROUP BY    
        [Unit Price],[Quantity],
        sil.[Document No_],
        sil.[Unit Volume],
        sil.[Shipment Date],
        sil.[Order No_],
        sil.[Customer Order No_],
        a.[Pirkejas]
ORDER BY     sil.[Shipment Date] DESC

我得到的结果:

TRV0093219 2015-12-22 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.2400 17.35 TRV0093219 2015-12-22 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.8140 121.00 TRV0093219 2015-12-21 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.0000 0.00 TRV0093219 2015-12-21 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.0000 0.00 TRV0093219 2015-12-21 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.0000 0.00

我需要得到的结果:

TRV0093219 2015-12-21 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 1.054 138.35

1 个答案:

答案 0 :(得分:1)

从GROUP BY中删除这些列并添加聚合函数:

WITH Agg1 AS(
SELECT  [Ship-to Name] As 'Pirkejas',
        [Order No_]
FROM [Artilux].[dbo].[Trivilita UAB$Sales Invoice Header]
)

SELECT  sil.[Document No_] as 'Pardavimo nr.',
    sil.[Shipment Date] as 'Siuntos data',
    sil.[Order No_] as 'Musu užsak. nr.',
    sil.[Customer Order No_]  AS 'Klientio užsak. nr.',
    a.[Pirkejas],
    SUM(CAST(sil.[Unit Volume]*sil.[Quantity] AS DECIMAL(16,4))) AS 'Tūris',
    SUM(CAST(sil.[Unit Price]*sil.[Quantity] AS DECIMAL(16,2))) AS 'Suma €'

FROM [Artilux].[dbo].[Trivilita UAB$Sales Invoice Line] sil

LEFT JOIN Agg1 a
ON a.[Order No_] = sil.[Order No_]

WHERE sil.[Sell-to Customer No_] = 'PRK0820' 
AND sil.[Shipment Date] > '2015-09-01 00:00:00.000'
AND sil.[Shipment Date] <= dateadd(day,datediff(day,0,GETDATE()),0)  AND sil.[Document No_] = 'TRV0093219'
GROUP BY    
        sil.[Document No_],
        sil.[Shipment Date],
        sil.[Order No_],
        sil.[Customer Order No_],
        a.[Pirkejas]
ORDER BY     sil.[Shipment Date] DESC