使用total和其他高级sql从多个表中选择数据
我的数据库中有表下结构使用total和其他高级sql从多个表中选择数据,sql,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
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 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;
我将留给您添加
加入
以引入名称。您可以使用下面的查询
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
您可以使用下面的查询
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
我删除了不兼容的数据库标记。只标记您真正使用的数据库。您在这里标记了几个RDBMS(
sql server
和t-sql
,mysql
和sqllite
),这是正确的吗?这看起来不像t-SQL。我删除了不兼容的数据库标记。只标记您真正使用的数据库。您在这里标记了几个RDBMS(sql server
和t-sql
,mysql
和sqllite
),这是正确的吗?这看起来不像t-SQL。