将函数应用于所有查询

时间:2015-07-27 20:50:54

标签: sql-server

我在一个主查询中有200个查询。而不是使用WHERE函数在每个查询中拉一个月,如何在顶部添加一个语句,以便将其应用于所有查询?

e.g。正如您可以看到WHERE函数,我只想要一段时间的数据。而不是每个查询都有一个WHERE函数来拉取某个日期,我可以使用什么,所以我只使用一个条件行来应用于以下所有查询?

--GL387903
    drop table #GL387903
select lmf.[Lease_Key],
sum (Cash_Excess_Mileage_Fee_Amt * -1) as Excess_Mileage__Comm_387903
into #GL387903
from dm_servicing.Lease.Vw_Lease_Month_Extend_Fact lmf
join dm_servicing.dbo.vw_Portfolio_Channel_Dim pcd on lmf.Portfolio_Channel_Key = pcd.Portfolio_Channel_Key
join [EDW].[dbo].[Pool_Detail] le on le.[Pool_Key] = lmf.pool_key
Where lmf.Month_Key = 201505
and pcd.Finance_Channel_Desc in ('Chrysler Comm Fleet Lease Non Eligible', 'Chrysler Comm Fleet Lease Eligible')
and le.Effective_Thru_Date = '9999-12-31' and le.Owned_Ind = 'y'
group by lmf.[Lease_Key]
having sum (Cash_Excess_Mileage_Fee_Amt * -1) <> 0
order by lease_key

--GL387904
drop table #GL387904
select lmf.[Lease_Key],
sum (Cash_Wear_And_Tear_Amt * -1) as Cash_Wear_And_Tear_Amt__Comm_387904
into #GL387904
from dm_servicing.Lease.Vw_Lease_Month_Extend_Fact lmf
join dm_servicing.dbo.vw_Portfolio_Channel_Dim pcd on lmf.Portfolio_Channel_Key = pcd.Portfolio_Channel_Key
join [EDW].[dbo].[Pool_Detail] le on le.[Pool_Key] = lmf.pool_key
Where lmf.Month_Key = 201505
and pcd.Finance_Channel_Desc in ('Chrysler Comm Fleet Lease Non Eligible', 'Chrysler Comm Fleet Lease Eligible')
and le.Effective_Thru_Date = '9999-12-31' and le.Owned_Ind = 'y'
group by lmf.[Lease_Key]
having sum (Cash_Wear_And_Tear_Amt * -1) <> 0
order by lease_key

1 个答案:

答案 0 :(得分:0)

-- Create a temp table for all the subsequesnt queries to use
-- Do all the SUMming in this query. You need a SUM for each of the following queries.
-- This assumes that all those queries have similar WHERE clauses as in your example.

SELECT
  lmf.[Lease_Key],
  SUM(Cash_Excess_Mileage_Fee_Amt * -1) AS Excess_Mileage__Comm_387903,
  SUM(Cash_Wear_And_Tear_Amt * -1) AS Cash_Wear_And_Tear_Amt__Comm_387904,
  ... etc
INTO
  #temp
FROM
  dm_servicing.Lease.Vw_Lease_Month_Extend_Fact lmf
  JOIN dm_servicing.dbo.vw_Portfolio_Channel_Dim pcd
    ON lmf.Portfolio_Channel_Key = pcd.Portfolio_Channel_Key
  JOIN [EDW].[dbo].[Pool_Detail] le
    ON le.[Pool_Key] = lmf.pool_key
WHERE
  lmf.Month_Key = 201505
  AND pcd.Finance_Channel_Desc IN ( 'Chrysler Comm Fleet Lease Non Eligible',
                                    'Chrysler Comm Fleet Lease Eligible' )
  AND le.Effective_Thru_Date = '9999-12-31'
  AND le.Owned_Ind = 'y'
GROUP BY
  lmf.[Lease_Key]


-- Now all the following queries that create your GLs are much simpler
-- and do not require updating a WHERE clause each new month.

--GL387903
SELECT
  lmf.[Lease_Key],
  Excess_Mileage__Comm_387903
INTO
  #GL387903
FROM
  #temp
WHERE
  Cash_Excess_Mileage_Fee_Amt <> 0

--GL387904
SELECT
  lmf.[Lease_Key],
  Cash_Wear_And_Tear_Amt__Comm_387904
INTO
  #GL387904
FROM
  #temp
WHERE
  Cash_Wear_And_Tear_Amt__Comm_387904 <> 0

... etc