在一个查询中添加两个Sql查询的结果?

时间:2015-10-21 18:04:18

标签: mysql

基本上我有两个返回所需结果的查询

但是我需要将这两个结果添加到"子查询"(如果那甚至是一个术语)。

这两个有效的查询:

SELECT SUM(Amount) AS Amount FROM AccountTransactions
INNER JOIN AccountTransactionDocuments
ON AccountTransactions.AccountTransactionDocumentId = AccountTransactionDocuments.Id
where AccountTransactionDocuments.Date > '{Start}' and AccountTransactionDocuments.Date < '{End}' and AccountTransactions.Name = 'Cash Payment';

SELECT SUM(case when TenderedAmount > 0 then TenderedAmount else 0 end) AS TenderedAmount FROM Payments
where Payments.Date > '{Start}' and Payments.Date < '{End}' and  Payments.Name = 'Cash' ;

这是我试过的副本。我不知道在最后的FROM

中放什么
SELECT
       (SELECT SUM(case when TenderedAmount > 0 then TenderedAmount else 0 end) AS TenderedAmount FROM Payments
where Payments.Date > '{Start}' and Payments.Date < '{End}' and  Payments.Name = 'Cash')
       +
       (SELECT SUM(Amount) AS Amount FROM AccountTransactions
INNER JOIN AccountTransactionDocuments
ON AccountTransactions.AccountTransactionDocumentId = AccountTransactionDocuments.Id
where AccountTransactionDocuments.Date > '{Start}' and AccountTransactionDocuments.Date < '{End}' and AccountTransactions.Name = 'Cash Payment') 
AS Cash Drawer 
FROM Payments;

任何想法? 或者这甚至可能吗?

编辑: AS Cash Drawer 中的空间导致语法错误。 也删除了最后一个FROM,它完美的感谢

2 个答案:

答案 0 :(得分:0)

如果您的顶部和底部查询都有效,那么您可以将它们与union all一起猛击,然后对这两个结果进行求和。我已将提交的金额更改为底部查询中的金额,以便将它们联系在一起。

$('.empNumber').change(function(){
    $.getJSON('getEmpInfo',{...},function(response){
        $('.empName').val(response.empName);
        ...
    }
})

答案 1 :(得分:0)

从外部查询中删除FROM Payments。这将导致它为Payments表中的每一行执行两个子查询,并返回与该表中的行一样多的总和副本。