如何在 SQL 查询中按组计算行数
How to count rows by group in a SQL query
我有一个 SQL 查询 returns 数据,其中包括报价类型和客户信息。有 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
我认为使用 window 函数很容易。
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
结果如下:
希望对您有所帮助。
我有一个 SQL 查询 returns 数据,其中包括报价类型和客户信息。有 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
我认为使用 window 函数很容易。
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
结果如下:
希望对您有所帮助。