Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL查询中按组计算行数_Sql_Sql Server 2012_Ssrs 2012 - Fatal编程技术网

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

如何在SQL查询中按组计算行数,sql,sql-server-2012,ssrs-2012,Sql,Sql Server 2012,Ssrs 2012,我有一个SQL查询,它返回的数据包括报价类型和客户信息。有4种类型的报价(开放式、死式、重新报价、项目)。我希望能够计算每个客户的每种类型。并计算总数。我还没有找到实现这一目标的方法 最终,我希望这能成为SSRS报告中的一个指标,这样我们就可以知道有多少报价(百分比)最终会变成一个项目 我在搜索中没有找到任何有效的东西。提前感谢您的建议。使用CTE WITH quoteTotal as ( Select customer, count(*) as customer_total

我有一个SQL查询,它返回的数据包括报价类型和客户信息。有4种类型的报价(开放式、死式、重新报价、项目)。我希望能够计算每个客户的每种类型。并计算总数。我还没有找到实现这一目标的方法

最终,我希望这能成为SSRS报告中的一个指标,这样我们就可以知道有多少报价(百分比)最终会变成一个项目

我在搜索中没有找到任何有效的东西。提前感谢您的建议。

使用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
有关以下数据:

我已经执行了下面的查询

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
结果如下:


我希望这会有所帮助。

下次尝试提供一个模式和一些数据,以便我们能够更好地理解问题并更快地给您答案-另外,请阅读并查找
COUNT
GROUP BY
对于我能给您的数据量有限表示抱歉。但是非常感谢你花时间提出这个问题。经过一些调整后,它正在以我想要的方式工作。您使用的是cte还是Windows版本?