1

如何获得每次更换纸张的总张数

例子:

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

连接和东西对我的真实查询更现实,但为这篇文章格式化以隐藏真实的字段和表名。

4

3 回答 3

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
于 2012-09-26T14:49:15.847 回答
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
于 2012-09-26T14:49:34.530 回答
0

看起来你需要一个 group-by 表达式:

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

是这样吗?

直流

于 2012-09-26T14:54:54.720 回答