sql—如何在表中的一行上获得两个单独的过程

cvxl0en2  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(335)

我已经设置了两个进程来向同一个表添加数据。我之所以做两个程序而不是一个是应管理层的要求。不过,目前它将数据添加到两个单独的行中,但如果可能的话,我希望它们位于同一行。这两个过程都带来了今天的日期,所以我想这是最好的方法,但我不能让它工作。这是第一个过程

INSERT INTO [BI_20200605_AllLoansDash] ([DATE], ALLMortgagesCount, AllMortgagesDistinctMemberCount,   MortgageBalances)
SELECT CONVERT(DATE, GETDATE()) AS Date,  COUNT(IIF (EMC.MC_PRIN_BAL > 0 AND EMC.MC_EXT_DROP_DATE IS NULL, EMC.MC_BORROWER_1_MBR_NBR, null) ) AS ALLMortgagesCount, 
COUNT(DISTINCT IIF(EMC.MC_PRIN_BAL > 0 AND EMC.MC_EXT_DROP_DATE IS NULL, EMC.MC_BORROWER_1_MBR_NBR, null) ) AS AllMortgagesDistinctMemberCount, 
SUM(IIF(EMC.MC_PRIN_BAL > 0 AND EMC.MC_EXT_DROP_DATE IS NULL, EMC.MC_PRIN_BAL, null))As MortgageBalances
FROM EMC
WHERE EMC.MC_EXT_DROP_DATE IS NULL

这是第二个过程。

INSERT INTO [BI_20200605_AllLoansDash] ([DATE], ALLCreditCardCount, AllCreditCardDistinctMemberCount,  AllNewCreditCards ,  CreditCardsClosed,  CreditCardBalances)
SELECT 
CONVERT(DATE, GETDATE()) AS Date,  COUNT(IIF (ECC.CLOSE_DATE IS NULL AND ECC.BLOCK_CODE = ' ', ECC.SAVINGS_ACCT_NBR, null) ) AS ALLCreditCardCount, 
COUNT(DISTINCT IIF(ECC.CLOSE_DATE IS NULL AND ECC.BLOCK_CODE = ' ', ECC.SAVINGS_ACCT_NBR, null) ) AS AllCreditCardDistinctMemberCount, 
COUNT(CASE WHEN CONVERT(DATE, GETDATE()) = ECC.Open_Date AND ECC.BLOCK_CODE = ' ' THEN ECC.SAVINGS_ACCT_NBR ELSE NULL END) AS AllNewCreditCards,
COUNT(CASE WHEN CONVERT(DATE, GETDATE()) = ECC.CLOSE_DATE AND ECC.BLOCK_CODE = ' ' THEN ECC.SAVINGS_ACCT_NBR ELSE NULL END) AS CreditCardsClosed,
SUM(IIF(ECC.CLOSE_DATE IS NULL AND ECC.BLOCK_CODE = ' ', ECC.CURRENT_BAL, null))As CreditCardBalances

FROM ECC
WHERE ECC.BLOCK_CODE = ' '
2cmtqfgy

2cmtqfgy1#

insert必须创建一行,因此,如果希望有两个单独的存储过程包含insert,则将创建两行。如果希望聚合数据位于一行上,则有两种选择。第一个选项更可取,因为它更干净,并将批处理作业的逻辑保持在一起,以便将来进行维护(当管理层不可避免地要求另一段数据时):
1) 一个s.proc。在插入表之前连接两个查询的。
2) 有一个s.proc。执行插入和第二个s.proc。使用某个共享标识符执行更新,以查找要用新信息更新的现有行。这将导致插入s.proc的两个s.proc.s之间存在依赖关系。必须在更新s.proc之前运行。由于这种依赖性,此解决方案比方案1次优。

相关问题