如何在SQL查询中按组计算行数

时间:2015-10-07 21:59:06

标签: sql sql-server-2012 ssrs-2012

我有一个SQL查询,它返回包含报价类型和客户信息的数据。有4种类型的报价(Open,Dead,Requote,Project)。我希望能够为每个客户计算每种类型。并且还计算总数。我还没有找到实现这个目标的方法。

最终,我希望这可以在SSRS报告中进行衡量,以便我们可以判断有多少报价(百分比)最终变成了项目。

我的搜索中没有找到任何可行的内容。提前感谢任何建议。

2 个答案:

答案 0 :(得分:2)

使用CTE'

 WITH quoteTotal as (
      Select customer, count(*) as customer_total
      from customer
      group by customer
 ),
 typeQuote as (
      Select customer, quote_type, count(*) as quote_total
      from customer
      group by customer, quote_type
 )
 SELECT T.customer, T.quote_type, T.quote_total, Q.customer_total
 FROM typeQuote T
 INNER JOIN quoteTotal Q
    ON T.customer = Q.customer

我认为使用窗口函数很容易。

SELECT DISTINCT 
       customer, 
       quote_type,
       COUNT(*) OVER (partition by customer, quote_type order by customer) as type_total,
       COUNT(*) OVER (partition by customer order by customer) as customer_total
FROM customers

答案 1 :(得分:0)

对于以下数据:

enter image description here

我已经执行了以下查询

select  CustomerEntityId,QuoteType,
(select count(QuoteType) from Customers c
    where c.QuoteType=Customers.QuoteType
        and c.CustomerEntityId=customers.CustomerEntityId
    group by CustomerEntityId,QuoteType) as QuoteTypeTotal,
(select count(*) from Customers c1 
    where c1.CustomerEntityId=Customers.CustomerEntityId 
    group by CustomerEntityId) as CustomerTotal
from Customers
Group By CustomerEntityId,QuoteType
Order By CustomerEntityId

结果如下:

enter image description here

我希望它有所帮助。