如何在一个表上计算所有行和计数组

时间:2014-03-17 06:30:22

标签: sql-server stored-procedures

我写了像这样的SQL代码

    SELECT count(tn.[ProductName])  as ProductCount,tn.[CategoryID],tp.estbProducerID,tp.NewProducer
from [tpdcn] tp,[tpdtn] tn
left join [tpdcn]
on tn.parentid = tpdcn.libDocumentID
where tp.libdocumentID = @id
group by tn.[CategoryID],tp.estbProducerID

它的节目

   Product Count    CategoryID     estbProducerID
        2               1            810600017   
        9               2            810600017  
        2               3            810600017  
        2               4            810600017  
        1               5            810600017

但我需要更多一个字段来显示

 Product Count  CategoryID     estbProducerID     Product Count All   
        2               1            810600017                16
        9               2            810600017  
        2               3            810600017  
        2               4            810600017  
        1               5            810600017

我应该怎么做才能在一张桌子上做到

2 个答案:

答案 0 :(得分:0)

您可以使用OVER Clause (Transact-SQL)

count(*) over() as [Product Count All]

它将使用指定的分区计算行数。没有分区子句,它会计算所有行。

select count(T.[ProductName]) as ProductCount,
       T.CategoryID,
       T.estbProducerID,
       T.NewProducer,
       T.[Product Count All]
from (
     select tn.[ProductName],
            tn.[CategoryID],
            tp.estbProducerID,
            tp.NewProducer,
            count(*) over() as [Product Count All]
     from [tpdcn] tp,[tpdtn] tn
       left join [tpdcn]
         on tn.parentid = tpdcn.libDocumentID
     where tp.libdocumentID = @id
     ) as T
group by T.[CategoryID],
         T.estbProducerID

答案 1 :(得分:0)

试试这个:

;with cte as
(
SELECT count(tn.[ProductName])  as ProductCount,tn.[CategoryID],tp.estbProducerID,tp.NewProducer,
from [tpdcn] tp,[tpdtn] tn
left join [tpdcn]
on tn.parentid = tpdcn.libDocumentID
where tp.libdocumentID = @id
group by tn.[CategoryID],tp.estbProducerID
)

select *,sum(ProductCount) as  Product Count All  from cte group by tn.[CategoryID],tp.estbProducerID