简体   繁体   English

如何在SQL Server 2008上创建此条件分组字段?

[英]How can I create this conditional grouped field on SQL Server 2008?

Sorry for this question, but i cannot resolve this simple query. 抱歉这个问题,但我无法解决这个简单的查询。

I have this table: 我有这张桌子:

ID_Type      Item
-----------------
A            1
P            2
P            3
A            4
P            5
A            6

I need to calculate a "group" incremental counter based on ID_Type Field where This field has an "A" Value. 我需要根据ID_Type字段计算“组”增量计数器,其中该字段具有“ A”值。 This is the expected result: 这是预期的结果:

ID_Type      Item     Counter
-----------------------------
A            1        1
P            2        1
P            3        1
A            4        2
P            5        2
A            6        3

So every time a record with ID_Type='A' appear, I need to increment the counter. 因此,每次出现ID_Type ='A'的记录时,我都需要增加计数器。 Any help will be apreciated. 任何帮助将不胜感激。

In SQL Server 2012+, you can use a cumulative sum: 在SQL Server 2012+中,您可以使用累积总和:

select t.*,
       sum(case when id_type = 'A' then 1 else 0 end) over (order by item) as counter
from t;

This will be much more efficient than a correlated subquery approach, particularly on larger data sets. 这将比相关子查询方法更有效,尤其是在较大的数据集上。

One way is a subquery: 一种方法是子查询:

SELECT ID_Type, Item, (
  SELECT COUNT(*) FROM MyTable t2
  WHERE t2.Item <= t1.Item
  AND t2.ID_Type='A'
) AS Counter
FROM MyTable t1
ORDER BY Item ASC

This will work on any version of SQL Server. 这将适用于任何版本的SQL Server。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM