繁体   English   中英

从总计和其他高级sql的多个表中选择数据

[英]select data from multiple tables with total and other advance sql

我在数据库中具有以下表结构

table1
userid, userName, userAddress
1,Manish,india
2,rita,usa
3,mariya,vietnam

table2
userid(fk table1),transactionType,transactionDesc,transactionAmt
1,                  credit,        10 installations,    50
2,                  credit,         8 installations,    40
1,                  debit,          1 Cust. Complain,    5
1,                  debit,          2 uninformed leave, 10
3,                  credit,         2 installations,    10

我想建立一个SQL查询以选择以下结构化数据的方案

userName,balanceToPay
manish,       35
rita,         40
mariya,       10

我在做什么

datatable users = select * from table1

then foreach id in users
{  int total_credit = 0,total_debit=0
   datatable credits = select transactionAmt from table2 where transactionType='credit' and userid = id
   foreach TransAmt in credits
      total_credit += transAmt

   datatable debits = select transactionAmt from table2 where tansactionType = 'debit' and userid=id
   foreach TransAmt in debits
      total_debit += transAmt

   publish row userName, balanceToPay(total_credits - total_debits)
}

当数据量较小(最多30-40个用户)时,它运行良好,但现在需要3000-4000个用户

如果在3000个用户中应用相同的内容,则系统将等待更长的时间。

所以我需要专家来帮助我建立一个SQL查询

我尝试了SUM(),但是它只会减少内部循环。 所以我想寻求堆栈专家的帮助

您应该执行一个聚合查询:

select t2.userid,
       sum(case when t2.transactionType = 'credit' then transactionAmt
                when t2.transactionType = 'debit' then -transactionAmt
                else 0
           end) as balanceToPay
from table2 t2
group by t2.userid;

我将它留给您添加join以引入名称。

您可以使用以下查询

 SELECT  userName ,
    ( credit - debit ) AS balanceToPay
FROM    ( SELECT    A.userName ,
                SUM(CASE WHEN B.transactionType = 'credit'
                         THEN B.transactionAmt
                         ELSE 0
                    END) AS Credit ,
                SUM(CASE WHEN B.transactionType = 'debit'
                         THEN B.transactionAmt
                         ELSE 0
                    END) AS debit
      FROM      table1 A
                INNER JOIN table2 B ON A.userid = B.userid
                GROUP BY A.userName
    ) L

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM