如何在SQL Server的一行上添加列基础?

时间:2019-05-20 07:44:16

标签: sql sql-server

我有这张桌子

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

我如何将第1行和第8行合并为这样的结果

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

默认金额为eur 谢谢

2 个答案:

答案 0 :(得分:1)

您只需要在此处进行一些条件聚合:

--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

不需要CTE,我的咖啡还没有加入。

答案 1 :(得分:0)

尝试一下-

SELECT A.Row,A.Title,B.Code,A.RegDate,A.Amount,A.Amount_Usd FROM
(
    SELECT Row,Title,RegDate,
    ISNULL(SUM(CASE WHEN Code NOT IN (203251 ,201211) THEN Amount ELSE NULL END),0) Amount,
    ISNULL(SUM(CASE WHEN Code IN (203251 ,201211) THEN Amount ELSE NULL END),0)Amount_Usd
    FROM your_table
    GROUP BY Row,Title,RegDate
)A
INNER JOIN your_table B
ON A.Row = B.Row  and B.Code NOT IN (203251 ,201211)