获取每个ID更改的总计数

时间:2012-09-26 14:46:18

标签: tsql

如何获得每张纸张更改的总页数

示例:

select sheetID,
       ..
from SomeTable

结果看起来像这样:

sheetID
-----------
1000
1000
1000
1000
3000
3000
3000

所以我想要这样的东西:

select sheetID,
       count(sheetID) as TotalsheetCount
from SomeTable

我只是不知道如何在每次更改sheetID时打破计数。

所以我最终会以此为基础:

sheetID   TotalsheetCount
--------  -----------
1000          4
1000          4
1000          4
1000          4
3000          3
3000          3
3000          3

所以4是因为有4个1000,3是因为有3个3000。我想重复每行的sheetID的总计数,即使它正在重复,我想提供它。

更新,这是我对回复所做的事情,但是我现在得到的结果太多了,因为我没有在那之前添加那个分区计数的计数

   select MainTable.sheetID,
           COUNT(SomeTable.sheetID)OVER(PARTITION BY SomeTable.sheetID) AS TotalSheetCount
           table2.SomeField1,
           table2.SomeField1
    from MainTable
        join (select distinct Sales.SalesKey from SomeLongTableName_Sales) sales on sales.SheetKey = MainTable.sheetKey
        left outer join Site on MainTable.SiteKey = Site.SiteKey
        join Calendar on sales.Date >= Calendar.StartDate
             and sales.Date < Calendar.EndDate
        group by SomeTable.sheetID

连接和东西对我的真实查询更加真实,但为此帖子格式化以隐藏真实的字段和表名。

3 个答案:

答案 0 :(得分:1)

使用子查询中的GROUP BY子句选择计数:

SELECT sheetID,
       count(sheetID) as TotalsheetCount
FROM SomeTable
GROUP BY sheetID

这会使整个查询看起来像这样:

SELECT t.sheetID,
       counts.TotalsheetCount
FROM SomeTable t,
    (SELECT sheetID, count(sheetID) as TotalsheetCount FROM SomeTable GROUP BY sheetID) counts
WHERE t.sheetID = counts.sheetID

答案 1 :(得分:1)

您可能想要使用GROUP BY

SELECT sheetID,  COUNT(sheetID) AS TotalsheetCount
FROM dbo.SomeTable
GROUP BY sheetID
  

我想重复每一行的sheetID总数,   即使它在重复,我想提供

如果您至少使用SQL-Server 2005,则可以使用COUNT + OVER-clause的CTE,否则请使用子查询:

WITH CTE AS
(
   SELECT sheetID,  
      COUNT(sheetID)OVER(PARTITION BY sheetID) AS TotalsheetCount
   FROM SomeTable
)
SELECT sheetID, TotalsheetCount FROM CTE

答案 2 :(得分:0)

看起来你需要一个分组表达式:

select sheetID,
       count(*) as TotalsheetCount
from SomeTable
group by sheetID
是吗?

DC