提问人:Rwlsxn 提问时间:3/31/2023 最后编辑:Thom ARwlsxn 更新时间:4/3/2023 访问量:113
将临时表与现有查询联接
Join temp table with existing query
问:
我在 SSMS 中有 2 个查询,它们执行良好。 我需要将它们连接在一起,但我不确定如何连接(我是 T-SQL 的初学者)。
第一个脚本是从数据库中提取数据并转换一些列以创建我的事实表:
SELECT 'Policy' As PolicyType,
PolicyKey = [POLICY_NUMBER] + ' ' + CONVERT(VARCHAR(11), [TRNS_MSG_TS], 120),
"BATCH_ID",
"HISTORY_ID",
"POLICY_NUMBER",
"TRANSACTION_TYPE_CODE",
"POLICY_STATUS",
"COVER_WANTED",
"PACKAGE_TYPE",
"MIGRATION_INDICATOR",
"REFERRER_PREFIX",
"PROCESSOR_PREFIX",
"INTRODUCER_CHANNEL",
"INTRODUCER_SUBCHANNEL",
CAST("POLICY_VERSION_EFFECTIVE_START_DATE" AS DATE) As StartDate,
CAST("POLICY_EXPIRY_DATE" AS DATE) As PQExpiryDate,
CAST("CANCELLATION_DATE" AS DATE) As CancellationDate,
"FINALISED_PREMIUM_AMOUNT",
"ANNUAL_PREMIUM",
"TRANSACTIONAL_PREMIUM",
CAST("TRNS_MSG_TS" AS DATE) As TRNSDate,
CAST(LOADDATE AS DATE) As LoadDate,
OFFSET_IND,
FIX_IND
FROM Database.dbo."View1"
WHERE "POLICY_VERSION_EFFECTIVE_START_DATE" >= DATEADD(DAY,-1*DAY(GETDATE())+0, DATEADD(MONTH,-12,GETDATE()))
AND OFFSET_IND = 0
AND FIX_IND = 0
AND LOADDATE <= CAST(GETDATE() AS DATE)
第二个脚本是创建一个临时表,我想将其用作映射表:
SELECT DISTINCT "POLICY_NUMBER",
'Policy' as PolicyType,
CAST(MIN("TRNS_MSG_TS") As Date) As MinDate
into #FirstTransFlagMap
FROM Database.dbo."View1"
Group by "POLICY_NUMBER";
SELECT PolicyKey = ["POLICY_NUMBER"] + ' ' + CONVERT(VARCHAR(11),[MinDate], 120),
'1' as FirstTransFlag
FROM #FirstTransFlagMap;
我试图做的是将这两个脚本连接在一起,以便事实表输出上述所有列,以及 FirstTransFlag 列,其中值为 1(如果 PolicyKeys 匹配)和 0(如果它们不匹配)
谁能帮我把这两个脚本连接在一起以获得所需的结果?
我只是无法弄清楚如何格式化我的语法以加入这些脚本。第一次尝试使用临时表/字段,以及第一次尝试在 SSMS 中将表联接在一起
答:
0赞
lostinsarajevo
4/3/2023
#1
好吧,由于您的临时表已经创建,您可以按原样使用它。对于第一个查询,可以使用 CTE(公用表表达式)。
所以你会有类似的东西
WITH FirstQueryTabularDataCTE (all properties that you need)
AS
(
FirstQuery
)
SELECT f.Property1 from #FirstTransFlagMap AS f
JOIN FirstQueryTabularDataCTE AS CTE
ON f.Id = CTE.Id
显然,伪代码,但应该引导你朝着正确的方向前进。
评论
0赞
Rwlsxn
4/3/2023
非常感谢您的帮助!我会试一试,看看结果如何!@lostinsarajevo
评论
PRINT @@VERSION;