将总行添加到分组查询

时间:2015-07-14 13:56:58

标签: sql-server

我正在尝试将总行添加到分组查询中。我的查询如下:

SELECT T3.[SlpName], T1.[CardCode], T1.[CardName], T1.[ShipToCode], T2.[ItemCode], T2.[Dscription], 
SUM(T2.[Quantity]) AS 'Total Quantity',
MAX(T2.[Price]) AS 'Line Price', 
SUM(T2.[LineTotal]) AS 'Line Total', 
SUM(T2.[GrssProfit]) AS 'Gross Profit' 
FROM OCRD T0 INNER JOIN OINV T1 ON T0.[CardCode] = T1.[CardCode] INNER JOIN INV1 T2 ON T1.[DocEntry] = T2.[DocEntry] INNER JOIN OSLP T3 ON T0.[SlpCode] = T3.[SlpCode]
WHERE T3.[SlpName] = 'Name' AND T1.[createdate] >= DATEADD(day,-7, GETDATE())
GROUP BY T3.[SlpName], T1.[CardCode], T1.[CardName], T1.[ShipToCode], T2.[ItemCode], T2.[Dscription].

我想要的是SUM行的总行 - 实际上是总和的总和。

我尝试使用Union子句添加总计,但这会给我一条错误消息。当我使用ROLLUP函数时,它汇总了每一行,而不仅仅是我需要汇总的行。有人可以帮忙吗?

非常感谢。

2 个答案:

答案 0 :(得分:1)

如果你通过提及非总和列为null来进行没有该组的联合,它应该正常工作如下:

SELECT  T3.[SlpName]
    ,   T1.[CardCode]
    ,   T1.[CardName]
    ,   T1.[ShipToCode]
    ,   T2.[ItemCode]
    ,   T2.[Dscription]
    ,   SUM(T2.[Quantity]) AS 'Total Quantity'
    ,   MAX(T2.[Price]) AS 'Line Price'
    ,   SUM(T2.[LineTotal]) AS 'Line Total'
    ,   SUM(T2.[GrssProfit]) AS 'Gross Profit' 
FROM OCRD T0 
INNER JOIN 
    OINV T1 
ON T0.[CardCode] = T1.[CardCode]
INNER JOIN
    INV1 T2
ON T1.[DocEntry] = T2.[DocEntry]
INNER JOIN OSLP T3
ON T0.[SlpCode] = T3.[SlpCode]
WHERE T3.[SlpName] = 'Name'
AND     T1.[createdate] >= DATEADD(day,-7, GETDATE())
GROUP BY T3.[SlpName]
    ,   T1.[CardCode]
    ,   T1.[CardName]
    ,   T1.[ShipToCode]
    ,   T2.[ItemCode]
    ,   T2.[Dscription]
UNION
SELECT  NULL AS [SlpName]
    ,   NULL AS [CardCode]
    ,   NULL AS [CardName]
    ,   NULL AS [ShipToCode]
    ,   NULL AS [ItemCode]
    ,   NULL AS [Dscription]
    ,   SUM(T2.[Quantity]) AS 'Total Quantity'
    ,   NULL AS 'Line Price'
    ,   SUM(T2.[LineTotal]) AS 'Line Total'
    ,   SUM(T2.[GrssProfit]) AS 'Gross Profit' 
FROM OCRD T0 
INNER JOIN 
    OINV T1 
ON T0.[CardCode] = T1.[CardCode]
INNER JOIN
    INV1 T2
ON T1.[DocEntry] = T2.[DocEntry]
INNER JOIN OSLP T3
ON T0.[SlpCode] = T3.[SlpCode]
WHERE T3.[SlpName] = 'Name'
AND     T1.[createdate] >= DATEADD(day,-7, GETDATE())

答案 1 :(得分:0)

也许是这样的。但它完全未经测试 - 因此根本无法保证: - )

$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];