2015-10-07 23 views
1

我有一個SQL查詢,它返回包含報價類型和客戶信息的數據。有4種類型的引號(Open,Dead,Requote,Project)。我希望能夠爲每個客戶計算每種類型。也算總數。我還沒有找到一種方法來實現這一點。如何在SQL查詢中按組計數行

最終,我希望通過SSRS報告進行衡量,以便我們可以確定有多少報價(百分比)最終轉化爲項目。

我在我的搜索中找不到任何有效的東西。提前感謝您的任何建議。

+1

下一次嘗試提供 \t [** ** SqlFiddle(http://sqlfiddle.com/#!15/5368b/6)與模式和一些數據,以便我們能夠更好地理解這個問題,並給你回答 \t快得多 - 也請閱讀[**如何問**](http://stackoverflow.com/help/how-to-ask) \t和[**如何創建一個最小,完成,以及可驗證的示例。**](http://stackoverflow.com/help/mcve) –

+0

查找「COUNT」和「GROUP BY」 – Morpheus

回答

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 
+0

抱歉,我能夠爲您提供的數據量有限。但是非常感謝您花時間提出這個問題。經過一些調整後,它正在按照我想要的方式工作。 –

+0

您是否使用cte或window版本? –

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

我希望它有幫助。