如何在SQL SERVER中按名称分组Total

时间:2016-09-20 12:28:15

标签: sql sql-server tsql reporting-services

我有这样的表

DECLARE @T Table 
(
  EmployeDesc VARCHAR(20),
  Empname Varchar(50),
  headOffice INT,
  SubOffice INT
);

样本数据

INSERT INTO @T(EmployeDesc, Empname, headOffice, SubOffice) VALUES 
('Sale','Rob',2,3),
('Discount','Rob',6,10),
('Sale','BOB',2,3),
('Discount','BOB',2,3);

我们如何在SQL server中实现这一目标

EmployeDesc Empname headOffice  SubOffice

Sale        Rob         2          3
Discount    Rob         6         10
  **Rob Total**         8         13
Sale        BOB         2          3
Discount    BOB         2          3
  **BOB Total**         4          6

我们可以使用UNION ALL或Running Totals,但还有其他方法可以做到这一点。

任何人都可以建议我

3 个答案:

答案 0 :(得分:5)

您可以使用grouping sets

select EmployeDesc, Empname,
       sum(headOffice) as headOffice, sum(SubOffice) as SubOffice
from @T
group by grouping sets ( (EmployeDesc, Empname), (EmpName) );

答案 1 :(得分:3)

使用使用ROLLUP进行分组:

;with X AS
(
    SELECT
        EmployeDesc, 
        Empname,
        SUM(headOffice) AS headOffice,
        SUM(SubOffice) AS SubOffice
    FROM @T
    GROUP BY Empname,EmployeDesc WITH ROLLUP
)
SELECT  
    CASE ISNULL(EmployeDesc,'') WHEN '' THEN '**'+Empname+ ' Total**' ELSE EmployeDesc END AS EmployeDesc, 
    CASE ISNULL(EmployeDesc,'') WHEN '' THEN '' ELSE Empname END AS Empname,    
    headOffice,
    SubOffice
FROM X
WHERE X.Empname IS NOT NULL

答案 2 :(得分:0)

SELECT [Group],
       [Name],
       SUM([SalesYTD]) AS 'Total Sales'
FROM #TempTable
GROUP BY [Group],
         [Name]
WITH ROLLUP

结果集:

╔═══════════════════════════════════════════════════════╗
║ Group                Name                 Total Sales ║
╠═══════════════════════════════════════════════════════╣
║ Europe               France                74569.00   ║
║ Europe               Germany               59456.00   ║
║ Europe               United Kingdom        78327.00   ║
║ Europe               NULL                 212352.00   ║
║ North America        Northwest            208774.00   ║
║ North America        Southeast            145477.00   ║
║ North America        Southwest            164232.00   ║
║ North America        NULL                 518483.00   ║
║ Pacific              Australia             93403.00   ║
║ Pacific              NULL                  93403.00   ║
║ NULL                 NULL                 824238.00   ║
╚═══════════════════════════════════════════════════════╝