2013-11-21 33 views
1

計數基於組我有表請求需要獲取彙總行數和行通過在單一查詢

REQUESTID` | ProductID 
---------------------------- 
1    |  1 
2    |  1 
3    |  4 
4    |  4 
5    |  4 ` 

現在我需要輸出爲單查詢

ProductID  |  Count  |  Total 
---------------------------------------------------- 
     1   |   2   |  5 
     4   |   3   |  5 

基本上內,我需要計算總請求中的產品百分比有多少人喜歡特定產品。我需要這在單一的查詢進行

代碼我已經試過::

Alter Proc SP_Get_Product_History_Count 
AS 

Declare @Tot bigint 

Select @Tot = COUNT(RequestID) from Request 

Select 
    Pro.ProductName, 
    COUNT(Req.RequestID) /@Tot as Count 

From 
    Request As Req 
inner join 
    Product As Pro 
on 
    Req.ProductID = Pro.ProductID 
Group by Pro.ProductName 
+0

我可以通過使用一個額外的變量做上述情況,由從請求中選擇@tot = Count(ProductID),然後使用它。但我被要求通過單個查詢 –

+0

來做,但向我們展示代碼。我問你嘗試的原因是因爲SO不是代碼生成站點。 – SchmitzIT

+0

我剛剛添加了代碼,到目前爲止我嘗試過了,在這裏我使用了兩個Select Queries,並且我被要求通過單個查詢來完成 –

回答

1
;WITH x AS 
(
    SELECT ProductID, total = COUNT(*) OVER() 
    FROM dbo.REQUEST 
) 
SELECT 
    ProductID, 
    COUNT(*), 
    MAX(total), 
    1.0*COUNT(*)/MAX(total) 
FROM x 
GROUP BY ProductID; 

SQLFiddle demo

1
select productid, 
count(requestid) as [Count], 
(select count(requestid) from [Request]) as Total 
from [Request] 
group by productid