【问题标题】:How Do I collapse rows on null values in t-sql?如何在T-SQL中折叠零值的行?
【发布时间】:2018-04-26 08:11:09
【问题描述】:

我的查询情况很奇怪。我的目标是显示每个人的多笔交易的总存款和取款并显示出来。我得到了多行,我需要合并为一行。这一切都需要在一个查询中完成

SELECT
       lastname,
       firsname,
       case when upper(category) = 'W' then sum(abs(principal)) end as Withdrawal,
       case when upper(category) = 'D' then sum(abs(principal)) end as Deposit,
       description
FROM
       table1 
       JOIN table2 ON table1.id = table2.id 
       JOIN table3 ON table2.c = table3.c 
WHERE 
       description = 'string'
GROUP BY
       lastname,
       firstname,
       description,
       category

我的结果是

 lastname    firstname    Withdrawal    Deposit    description
 john         smith       null           140.34    string
 john         smith       346.00          null     string
 jane         doe         null           68.03     string
 jane         doe         504.00          null     string

我正在寻找

 lastname    firstname    Withdrawal    Deposit    description
 john         smith       346.00        140.34     string
 jane         doe         504.00        68.03      string

将委托人添加到组中不起作用。任何解决此问题的帮助将不胜感激!

【问题讨论】:

  • 从分组依据中删除类别并在案例外求和?

标签: sql tsql rows collapse


【解决方案1】:

使用条件聚合。 . . casesum() 的参数:

select lastname, firsname,
       sum(case when upper(category) = 'W' then abs(principal) end) as Withdrawal,
       sum(case when upper(category) = 'D' then abs(principal) end) as Deposit, 
       description
from table1 join
     table2
     on table2.id = table1.id join
     table3 
     on table3.c = table2.c
where description = 'string'
group by lastname, firstname, description

【讨论】:

  • 有用的解决方案。
  • 是的,这与 xQbert 的建议相结合!谢谢!
【解决方案2】:

使用子查询的解决方案

select t.lastname, t.firsname,sum(t.Withdrawal) Withdrawal ,sum(t.Deposit) Deposit,t.description from(
select lastname, firsname,
       isnull(case when upper(category) = 'W' then abs(principal) end,0) as Withdrawal,
       isnull(case when upper(category) = 'D' then abs(principal) end,0) as Deposit,
description
from table1 join
     table2
     on table2.id = table1.id join
     table3
     on table3.c = table2.c
where description = 'string'
)t group by t.lastname, t.firstname, t.description, t.category

【讨论】:

    【解决方案3】:

    试试这个:

    SELECT lastname,firsname,
           SUM(case when upper(category) = 'W' then abs(principal) end) as Withdrawal,
           SUM(case when upper(category) = 'D' then abs(principal) end) as Deposit,
           description
    FROM
           table1 
           JOIN table2 ON table1.id = table2.id 
           JOIN table3 ON table2.c = table3.c 
    WHERE 
           description = 'string'
    GROUP BY
    lastname,firstname,description
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-21
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多