有没有办法合并这两个简单的查询

时间:2012-01-31 00:32:56

标签: sql sql-server database sql-server-2008 tsql

我确信我认为这是可能的,但有没有办法合并这两个查询?

查询#1:

select distinct 
    count(l.lease_id) as 'Count_Transactions_ALL', 
    sum(l.net_area) as 'Total_Area_ALL'
from
    lease_deal.lease l
where
    l.deal_approved_date >= @dateFrom   
    and l.deal_approved_date  <= @dateTo
    and l.lease_status in(@leaseStatus)

查询#2:

select distinct 
    count(l.lease_id) as 'Count_Transactions_NEW', 
from
    lease_deal.lease l
where
    l.deal_approved_date >= @dateFrom   
    and l.deal_approved_date  <= @dateTo
    and l.lease_status in(@leaseStatus)
    and l.negotiation_type = 'NEW'

我想要的输出是:

Count_Transactions_ALL,Total_Area_All,Count_Transactions_NEW

x,y,z

2 个答案:

答案 0 :(得分:8)

尝试这样的事情:

select 
    count(l.lease_id) as 'Count_Transactions_ALL', 
    sum(l.net_area) as 'Total_Area_ALL',
    sum(case l.negotiation_type 
        when 'NEW' then 1 else 0 end) 
    as Count_Transactions_NEW
from
    lease_deal.lease l
where
    l.deal_approved_date >= @dateFrom   
    and l.deal_approved_date  <= @dateTo
    and l.lease_status in(@leaseStatus)

答案 1 :(得分:1)

select distinct 
        count(l.lease_id) as 'Count_Transactions_ALL', 
        sum(l.net_area) as 'Total_Area_ALL', 
       sum( if(l.negotiation_type = 'NEW', 1, 0)) as 'Count_Transactions_New'
    from
        lease_deal.lease l
    where
        l.deal_approved_date >= @dateFrom   
        and l.deal_approved_date  <= @dateTo
        and l.lease_status in(@leaseStatus)