一个带有两个where子句的查询中的两个sql总和[重复]

Posted

技术标签:

【中文标题】一个带有两个where子句的查询中的两个sql总和[重复]【英文标题】:Two sql sums in one query with two where clauses [duplicate] 【发布时间】:2016-04-27 19:51:20 【问题描述】:

您好,我想将两条 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

任何帮助将不胜感激。

谢谢

【问题讨论】:

【参考方案1】:

您可以将这两行与CROSS JOIN 组合在一起。通常建议不要这样做,因为如果您交叉连接两个表,每个表有 M 行和 N 行,您会在结果中得到 MxN 行(可以是 lot),但在这种情况下,您知道一个事实M 和 N 都是 1,所以 MxN 也是 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

【讨论】:

【参考方案2】:

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

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

【讨论】:

以上是关于一个带有两个where子句的查询中的两个sql总和[重复]的主要内容,如果未能解决你的问题,请参考以下文章

使用多个 WHERE 子句和 GROUP BY 销售人员访问 SQL、聚合总和

如何高效查询带有两个 WHERE 子句的表(Android Room)

每个总和都带有 WHERE 子句的 SUM 函数?

带有相关数据的where子句的Linq查询

SQL 合并总和选择一个结果

SQL 在表的两个副本之间留下了带有 WHERE 子句依赖关系的自连接