Group By返回多个不同的分组结果SQL Server

时间:2015-03-09 18:35:30

标签: sql-server group-by aggregation

我不认为这会太粗糙,虽然我没有在问题中看到它并回答问题。

我正在寻找一种按销售人员分组的两种不同类型的销售方式。

类似

Name PendingORders CompletedOrders TotalOrders

首先按名称分组,计数类型= P,计数= C,然后加上类型= P和计数= C.

虽然此报告中只有两种类型的订单,但从技术上讲,标准只是名称所有订单的计数。

我的表格看起来像这样

Name|Order#|Type
Jane| 1    | C
Jane| 2    | P
Jane| 3    | P
Fred| 4    | P
Fred| 5    | P

希望查询会生成

Name|TotalOrder|Pending|Completed 
Jane|3         |2      |1
Fred|2         |2      |0

非常感谢提前

3 个答案:

答案 0 :(得分:1)

使用Conditional Aggregate

select Name
       TotalOrder = count(Name),
       Completed = count(case when type = 'C' then 1 end),
       PENDING = count(case when type = 'P' then 1 end)
From yourtable
group by Name

或使用Pivot

SELECT Name,
       TotalOrder,
       Completed = C,
       PENDING = P
FROM   (SELECT *,
               TotalOrder=Count(1)OVER(partition BY name)
        FROM   Yourtable) a
       PIVOT (Max(order#)
             FOR type IN ([C],
                          [P]))pv 

答案 1 :(得分:1)

因此,您基本上只需按销售人员进行分组,并为每个分组计算三种不同的聚合。这完全是直截了当的:

SELECT
  Name,
  count(*) AS TotalOrder,
  SUM(CASE Type WHEN 'P' THEN 1 ELSE 0 END) AS Pending,
  SUM(CASE Type WHEN 'C' THEN 1 ELSE 0 END) AS Completed,
FROM orders
GROUP BY name;

答案 2 :(得分:0)

我使用临时表解决了你的问题。您必须使用条件(CASE WHEN)语句来计算数学然后按名称分组。

CREATE TABLE #Orders (
Name VARCHAR(25) NULL , 
OrderNumber INT NULL , 
OrderType CHAR(1) NULL )



INSERT INTO #Orders (Name, OrderNumber , OrderType)
    VALUES ( 'Jane' , 1 , 'C') , 
           ( 'Jane' , 2 , 'P') , 
           ( 'Jane' , 3 , 'P') , 
           ( 'Fred' , 4 , 'P') , 
           ( 'Fred' , 5 , 'P') 



 SELECT Name , 
        COUNT(*) AS TotalOrder , 
        SUM(CASE OrderType WHEN 'P' THEN 1 ELSE 0 END) AS Pending , 
        SUM(CASE OrderType WHEN 'C' THEN 1 ELSE 0 END) AS Completed  
   FROM #Orders
  GROUP BY Name 

 DROP TABLE #Orders