Skip to content
Advertisement

how to add column base on one row in sql server? [closed]

i have this table

Row Title   Code    RegDate     Amount
----------------------------------------------------------
1   typea   203170  1396/12/29  150760000000    --Eur
1   typea   203251  1396/12/29  169928736       --Usd
2   typeb   201310  1396/12/29  32794373868351
3   typec   201441  1396/12/29  899750000
6   typed   201216  1396/12/29  23411268063599
8   typee   201181  1396/12/29  86687000        --Eur
8   typee   201211  1396/12/29  81483719480611  --Usd
9   typef   201212  1396/12/29  52595043810
10  typeh   201213  1396/12/29  3630924097

how i can combine Row 1 and 8 to one row like this result

Row Title   Code    RegDate     Amount          Amount_Usd
----------------------------------------------------------
1   typea   203170  1396/12/29  150760000000    169928736
2   typeb   201310  1396/12/29  32794373868351  0
3   typec   201441  1396/12/29  899750000       0
6   typed   201216  1396/12/29  23411268063599  0
8   typee   201181  1396/12/29  86687000        81483719480611
9   typef   201212  1396/12/29  52595043810     0
10  typeh   201213  1396/12/29  3630924097      0

default amount is eur thanks

Advertisement

Answer

You just need some conditional aggregation here:

--Sample Data
WITH VTE AS(
    SELECT *
    FROM (VALUES(1   ,'typea',203170,'1396/12/29',150760000000),
                (1   ,'typea',203251,'1396/12/29',169928736),   
                (2   ,'typeb',201310,'1396/12/29',32794373868351),
                (3   ,'typec',201441,'1396/12/29',899750000),
                (6   ,'typed',201216,'1396/12/29',23411268063599),
                (8   ,'typee',201181,'1396/12/29',86687000),
                (8   ,'typee',201211,'1396/12/29',81483719480611),
                (9   ,'typef',201212,'1396/12/29',52595043810),
                (10  ,'typeh',201213,'1396/12/29',3630924097)) V([Row],Title,Code, RegDate, Amount))
--Solution
SELECT Row,
       Title,
       MIN(CASE WHEN Code NOT IN (203251,201211) THEN Code END) AS Code,
       RegDate,
       ISNULL(SUM(CASE WHEN Code NOT IN (203251,201211) THEN Amount END),0) AS Amount,
       ISNULL(SUM(CASE WHEN Code IN (203251,201211) THEN Amount END),0) AS Amount_Usd
FROM VTE
GROUP BY [Row],[Title],RegDate;

db<>fiddle

No need for a CTE, my coffee hadn’t kicked in.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement