在一个查询中有两个sql求和,其中有两个where子句

时间:2016-04-27 19:51:20

标签: mysql select casting sum

您好我想将两个sql语句合并为一个,这样数据就会显示在一个查询中。

以下sql查询工作正常:

SELECT SUM(CAST(CAST(Amount AS float) AS INT)) AS TotalSponsor
FROM Fees WHERE(Sponsor = 'True') 

&安培;

SELECT SUM(CAST(CAST(Amount AS float) AS INT)) AS TotalLoan
FROM Fees WHERE(StudentLoan = 'True') 

基本上我想加入它们,所以输出就像:

TotalSponsor   TotalLoan
10000          5000

任何帮助都将不胜感激。

由于

2 个答案:

答案 0 :(得分:1)

您可以将这两行与SELECT * FROM ( SELECT SUM(CAST(CAST(Amount AS float) AS INT)) AS TotalSponsor FROM Fees WHERE(Sponsor = 'True') ) AS x CROSS JOIN ( SELECT SUM(CAST(CAST(Amount AS float) AS INT)) AS TotalLoan FROM Fees WHERE(StudentLoan = 'True') ) AS y 合并。通常建议不要使用这些,因为如果你交叉连接两个表,每个表有M行和N行,你会得到结果中的MxN行(可以是 lot ),但在这种情况下你知道一个事实M和N都是1,所以MxN也是1.

{{1}}

答案 1 :(得分:1)

一个选项是条件聚合......

SELECT SUM(IF(f.Sponsor    ='True',CAST(CAST(Amount AS float) AS INT),0)) AS TotalSponsor
     , SUM(IF(f.StudentLoan='True',CAST(CAST(Amount AS float) AS INT),0)) AS TotalLoan
  FROM Fees f
 WHERE f.Sponsor = 'True'
    OR f.StudentLoan = 'True'

IF()函数将第一个参数计算为布尔值,如果计算结果为TRUE,则返回第二个参数,否则返回第三个参数。

您可以使用CASE表达式代替IF以获得等效行为......

 SUM(CASE WHEN  somecondition  THEN  somevalue  ELSE 0 END)

或者,您可以在外部查询的SELECT列表中使用sbqueries,如下所示:

SELECT ( SELECT SUM(CAST(CAST(Amount AS float) AS INT))
           FROM Fees
          WHERE(Sponsor = 'True') 
       ) AS TotalSponsor
     , ( SELECT SUM(CAST(CAST(Amount AS float) AS INT))
           FROM Fees
           WHERE(StudentLoan = 'True')
       ) AS TotalLoan

或者,您可以将查询用作内嵌视图

SELECT s.TotalSponsor
     , l.TotalLoan
  FROM ( SELECT SUM(CAST(CAST(Amount AS float) AS INT)) AS TotalSponsor
           FROM Fees WHERE(Sponsor = 'True') 
       ) s
 CROSS
  JOIN  ( SELECT SUM(CAST(CAST(Amount AS float) AS INT)) AS TotalLoan
            FROM Fees WHERE(StudentLoan = 'True')
       ) l