混合两个SQL查询

时间:2012-12-05 18:51:38

标签: sql

我想混合2个sql查询,一个用于获取特定年份的总金额,另一个用于了解特定年份特定月份的金额

SELECT SUM(money) As Anual FROM Deposito WHERE Year(FechaDeposito)=2011

SELECT SUM(money) As monthly FROM Deposito WHERE Year(FechaDeposito)= 2011 AND Month(FechaDeposito)=10

如何以最有效的方式做到这一点?

1 个答案:

答案 0 :(得分:3)

只需合并两个查询即可

SELECT SUM(money) As Anual,
       SUM(CASE WHEN Month(FechaDeposito)=10 THEN money else 0 end) as monthly
  FROM Deposito
 WHERE Year(FechaDeposito)=2011
然而,它会表现得非常糟糕。理想情况下,您需要FechaDeposito上的索引,并构建日期范围以进行测试,而不是在列上运行函数,例如

SELECT SUM(money) As Anual,
       SUM(CASE WHEN Month(FechaDeposito)=10 THEN money else 0 end) as monthly
  FROM Deposito
 WHERE FechaDeposito >= '2011-01-01' and FechaDeposito < '2012-01-01'