申请多个" Where"查询SQL SERVER

时间:2016-05-09 09:57:35

标签: sql sql-server database where-clause

我想

我有这个问题:

select 

SUM(fact.cheques) as TotalChequeAmount,
SUM(fact.revenusIntermediationToDate + fact.cheques ) as YTD ,
SUM(fact.revenusIntermediationToDate + fact.cheques ) as YTDN1,
SUM(revenusIntermediationToDate) as TotalRevenuIntermediationToDate,

acc.beCompanyCode as Codecompany,
acc.Country as Pays,
acc.Name as Name,
acc.AccountTypeSec as AccountType,
acc.Segmentation as Segmentation,
acc.City as City,
acc.OfficialGroup as OfficialGroup , 
acc.ActualYearBudget as Budget2016,
acc.SegmentationResSec as SegmentSecurities

from dbo.Fact_Profit_And_Loss fact
left outer join dbo.Dim_Accounts acc  on ( acc.Accounts_TechKey = fact.FK_Account)
left outer join dbo.DimTemps time1 on (time1.Temps_PK = fact.FK_Time)
where YEAR(time1.Date) = 2016
group by acc.beCompanyCode, acc.Country , acc.Name , acc.AccountTypeSec , acc.Segmentation ,
acc.City , acc.OfficialGroup , acc.ActualYearBudget, acc.SegmentationResSec 

问题是我想为列YTD应用过滤器Year = 2016 列YTDN1的另一个过滤器Year = 2015。

是否有可能在一个Sql查询中为两列定义两个where子句?

TotalChequeAmount   YTD         YTDN1               Codecompany
0.00                6541.2826   6541.2826           2513
0.00                0.00        0.00                2541
0.00                7350.9433   7350.9433           2547

1 个答案:

答案 0 :(得分:3)

使用条件聚合

select SUM(fact.cheques) as TotalChequeAmount,
       SUM(CASE 
              WHEN YEAR(time1.Date) = 2016 
                 THEN fact.revenusIntermediationToDate + fact.cheques 
              ELSE 0 
           END) as YTD ,
       SUM(CASE 
              WHEN YEAR(time1.Date) = 2015 
                 THEN fact.revenusIntermediationToDate + fact.cheques 
              ELSE 0 
           END) as YTDN1,
       SUM(revenusIntermediationToDate) as TotalRevenuIntermediationToDate,    
       acc.beCompanyCode as Codecompany,
       acc.Country as Pays,
       acc.Name as Name,
       acc.AccountTypeSec as AccountType,
       acc.Segmentation as Segmentation,
       acc.City as City,
       acc.OfficialGroup as OfficialGroup , 
       acc.ActualYearBudget as Budget2016,
       acc.SegmentationResSec as SegmentSecurities    
from dbo.Fact_Profit_And_Loss fact
left outer join dbo.Dim_Accounts acc  
   on ( acc.Accounts_TechKey = fact.FK_Account)
left outer join dbo.DimTemps time1 on (time1.Temps_PK = fact.FK_Time)
where YEAR(time1.Date) IN (2015, 2016)
group by acc.beCompanyCode, acc.Country , 
         acc.Name , acc.AccountTypeSec , 
         acc.Segmentation , acc.City , 
         acc.OfficialGroup , acc.ActualYearBudget, 
         acc.SegmentationResSec 

上述查询的字段YTD返回2016年的结果,字段YTDN1返回2015年的结果。SUM的其他字段返回两年的总计。

相关问题