Question

The data in my table looks like this:

AUDTORG | SEQUENCENO | LINE | REFERENCE | AMOUNT | 
--------------------------------------------------
ADX     | 1          | 422  | Wire1     | 10     | 
ADX     | 2          | 385  | Wire2     | 10     | 
ADX     | 2          | 335  | Wire25    | 10     | 
ADX     | 2          | 335  | Transfer  | 10     | 
BMD     | 1          | 555  | Wire4     | 10     | 

I have to: 1. concatenate: AUDTORG and SEQUENCENO 2. Count the occurence of the concatenated field NewID.

This is the result I'm looking for:

AUDTORG | SEQUENCENO | LINE | REFERENCE | AMOUNT | NewID  | Occurence |
-----------------------------------------------------------------------
ADX     | 1          | 422  | Wire1     | 10     | ADX1   | 1         |
ADX     | 2          | 385  | Wire2     | 10     | ADX2   | 3         |
ADX     | 2          | 335  | Wire25    | 10     | ADX2   | 3         |
ADX     | 2          | 335  | Transfer  | 10     | ADX2   | 3         |
BMD     | 1          | 555  | Wire4     | 10     | BMD1   | 1         |

Here is the code I tried:

SELECT *, BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar) as NewID,
count(BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar)) as Occurence
FROM ADXDAT.dbo.BKENTD

All the rows must remain.

Was it helpful?

Solution

You can do this using window functions:

SELECT b.*,
      (b.AUDTORG + CAST(b.SEQUENCENO AS varchar(255)) )as NewID,
      count(*) over (partition by b.AUDTORG + CAST(b.SEQUENCENO AS varchar(255)) ) as Occurence
FROM ADXDAT.dbo.BKENTD b;

The over clause is used by window function. In this case, it counts everything in a group. The group is defined by the partition by clause. So, it counts everything with the same value of the new id.

OTHER TIPS

All rows must remain makes for the need for a subquery. This will obtain counts:

select BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar) as NewID, count(*) Occurence
FROM ADXDAT.dbo.BKENTD
group by BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar)

You now have the NewID and count for each. Join it back to your first statement and refer to it as a standard column (select * is now select a.* so you don't get the b.newID field):

SELECT a.*, BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar) as NewID, Occurence
FROM ADXDAT.dbo.BKENTD a
inner join 
(select BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar) as NewID, count(*) Occurence
FROM ADXDAT.dbo.BKENTD
group by BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar)) b
on a.NewID = b.NewID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top