如何解决如何在一个SQL语句中组合两个不同的SQL查询?
我有两个表:
Members
Member_id | Member_user_name | Member_account_id
和
Members_transaction
Member_id (sender) | Member_transaction_id | Member_account_id (recipient) | Amount | from_to
所有列都有数据,但是from_to是添加的新列。我想将发件人或收件人的用户名添加到from_to列中。
select member_user_name member_involved
from Members_transaction
left
join members
on members_transaction.member_account_id = members.member_account_id
SELECT member_transaction_id,mp.member_account_id,m.member_user_name,amount,CASE
-- when the amount starts with "-" such as "-100" it means paid to recipient
WHEN amount LIKE '-%' THEN 'Paid to' + member_involved
-- else it is received from the sender
ELSE ' Received from '+ member_involved
END AS from_to
FROM members_transaction MP (nolock)
LEFT
JOIN members M (NOLOCK)
ON M.MEMBER_ID = MP.MEMBER_ID
AND M.IS_USE = 1
WHERE MP.IS_USE = 1
由于条件不同(打开),如何将查找发件人或收件人的SQL查询合并到下面的SQL查询中?
解决方法
您可以与成员加入两次,一次为发送者名称,一次为接收者名称:
SELECT member_transaction_id,mp.member_account_id,m.member_user_name,amount,CASE
-- when the amount starts with "-" such as "-100" it means paid to recipient
WHEN amount LIKE '-%' THEN 'Paid to' + M2.member_user_name
-- else it is received from the sender
ELSE ' Received from '+ M.member_user_name
END AS from_to
FROM members_transaction MP (nolock)
LEFT JOIN members M (NOLOCK) ON M.MEMBER_ID = MP.MEMBER_ID AND M.IS_USE = 1
LEFT JOIN members M2 (NOLOCK) ON M2.member_account_id = MP.member_account_id AND M2.IS_USE = 1
WHERE MP.IS_USE = 1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。