我有一个表格,用于保存每个帐户的财务交易数据。
**FinTransMaster table:**
------------------------------------
|AcctID |FinTrnsCode|BusinessDay |
------------------------------------
|1234567 |INTRST |2017-09-09 |
------------------------------------
|1234567 |CHARGE |2017-09-08 |
------------------------------------
|1234567 |PYMNT |2017-09-01 |
------------------------------------
|1234567 |INTRST |2017-08-19 |
------------------------------------
|1234567 |INTRST |2017-08-09 |
------------------------------------
|1234567 |CHARGE |2017-08-04 |
------------------------------------
|1234567 |PYMNT |2017-08-01 |
------------------------------------
|1234567 |INTRST |2017-07-19 |
------------------------------------
我想选择上次每个帐户付款的时间。
所以我的代码如下:
SELECT AcctID
,[FinTransCode]
--,MAX([BusinessDay]) --Tried this line, doesn't work
--,ISNULL(MAX([BusinessDay]), 'Never Paid') Last_Paid --Tried this line too, doesn't work
,CASE WHEN ISNULL(MAX([BusinessDay]), 0) = 0 THEN 'Never Paid'
ELSE MAX([BusinessDay])
END Last_Paid
FROM [GEB_DWH].[dbo].[FinTransMaster]
WHERE AcctID = '1234567'
AND FinTransTypeCode = 'PYMT'
GROUP BY AcctID,[FinTransTypeCode]
这段代码不起作用,因为有些帐户永远不会付费。因此,有些帐户没有“PYMNT'该字段中的代码。它们在该字段中具有其他代码,但在该字段中没有PYMNT代码。因此,当我为该AcctID运行该代码时,我只得到标题而没有结果。
如何展示“从不付费”#39;在该字段中为该AcctID,以便我可以将其与另一个结果表连接?
通过加入AcctID,我最终想要获得的是:
-----------------------------------------------------------------
|AcctID |ContactName|Phone Number |Email Address |Last Payment |
-----------------------------------------------------------------
|1234567 |John Doe |123-123-1234 |test@123.com |Never Paid |
-----------------------------------------------------------------
答案 0 :(得分:0)
请尝试以下:
--Summary Stats by transaction type
SELECT
AcctID,
FinTrnsCode,
lastActivityDt = max(BusinessDay)
into #temp
FROM FinTransMaster
group by AcctID,FinTrnsCode
--Find out all customers with Pmts
SELECT
distinct
ACCTID,
LastPmtDate = LastActivityDt
into #temp2
FROM #temp where FinTrnsCode = 'PYMNT'
SELECT ACCTID,
LastPmtDate = cast(LastPmtDate as varchar(50)) FROM #temp2
union
--Get all customers with no pmt records
SELECT distinct ACCTID, 'Never Paid' FROM #Temp where ACCTID not in (SELECT distinct ACCTID FROM #temp2)
答案 1 :(得分:0)
只需将条件从where
移至select
:
SELECT AcctID,
MAX(CASE WHEN FinTransCode = 'PYMT' THEN BusinessDay END) as LastPayment
FROM [GEB_DWH].[dbo].[FinTransMaster]
GROUP BY AcctID;
如果有人没有付款,这会将值设置为NULL
。如果你想要一个字符串,你需要将日期转换为字符串,以便类型兼容。