简体   繁体   中英

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. 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. Any help will be apreciated.

In SQL Server 2012+, you can use a cumulative sum:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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