With the tables
CREATE TABLE ctab (id int,rate varchar(1)); -- claims table
INSERT INTO ctab (id,rate) VALUES
(1, 'N'),(2, 'N'),(3, 'N'),(4, 'F'),(5, 'N'),
(6, 'D'),(7, 'D'),(8, 'F'),(9, 'L');
CREATE TABLE rtab(id int,rate varchar(1), ratevale varchar(2));
INSERT INTO rtab (id,rate,ratevale) VALUES -- rates table
(1, 'N', 'NA'),(2, 'D', 'DH'),(3, 'F', 'FA'),(4, 'L', 'LD');
we can do the following:
SELECT t.id, CONCAT(ratevale,'-40-',RIGHT(CAST(i+1000 as char(4)),3)) rval
FROM (
SELECT CASE WHEN @r =rate THEN @i:=@i+1 ELSE @i:= 1 END i,
CASE WHEN @r!=rate THEN @r:=rate ELSE @r END r,
id id,rate rate
FROM (SELECT @i:=1,@r:='') v, ctab c
ORDER BY rate,id
) t
INNER JOIN rtab r ON r.rate=t.rate
ORDER BY id
and we get:
| id | rval |
|----|-----------|
| 1 | NA-40-001 |
| 2 | NA-40-002 |
| 3 | NA-40-003 |
| 4 | FA-40-001 |
| 5 | NA-40-004 |
| 6 | DH-40-001 |
| 7 | DH-40-002 |
| 8 | FA-40-002 |
| 9 | LD-40-001 |
Play around with it here: http://sqlfiddle.com/#!9/d9e3e/15
The basic idea is that we list the claims table, ordered by rate
and turn it into a derived table t
.
Having initialised @i
to 1
and @r
to ''
in the derived table v
we check whether @r=rate
and
- if so, we increment
@i
.
- otherwise (
ELSE
) we reset @i
to 1
and @r
to rate
.
This happens in the second CASE
clause.
We end up with a sequence column i
that starts counting for each value of rate
. In the outer SELECT
statement the derived table t
is then joined to the rates table rtab
and a different sorting order is applied.
Please note:
This solution can also be seen as an alternative solution to ROW_NUMBER() in MySQL . The above MySQL query in can easily be rewritten in MSSQL by applying row_number() over (partition...)
, see here: http://sqlfiddle.com/#!3/d9e3e/8