需要在单个查询中基于Group by获取Total Rows Count和Rows计数

时间:2013-11-21 08:00:14

标签: sql sql-server-2005

我有表REQUEST

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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