只是想检查是否有更简单的方法或更好的方式来编写以下查询?我必须联合加入大约10个表MMA_AUDITSUM_STG
在下面我只做了两个。是否可以一个接一个地输入所有列名称并包含来自MMA_SITE_MST
的联接?我使用SQL Server来存储数据。
SELECT
a.CLIENT_NAME AS [BRAND], a.SITE_NO AS [SITE NO],
a.SITE_NAME AS [SITE],
c.FILTER_1 AS [AREA], c.FILTER_2 AS [REGION],
a.MANAGER,
a.AUDIT_DATE AS [db.audit_date], a.THIS_AUDIT_SCORE AS [SCORE],
a.ALERTS_FLAG AS [ALERTS], a.REPEAT_FLAG AS [REPEAT ISSUES],
a.ACTION_PLAN_FLAG AS [ACTION PLAN FAILURE],
a.Cash, a.Revenue, a.Stock,
a.[Unaccounted Stock], a.[People & Payroll],
a.[Safe], a.[Security], a.[Petty Cash], a.[Tills],
a.[Bankings], a.[Sales], a.[Vouchers & Discounting],
a.[PDQ], a.[Administration],
a.[Stock Verification], a.[Stock Management], a.[Ordering]
FROM
MMA_AUDITSUM_STG_34 As a
INNER JOIN
MMA_SITE_MST AS c ON a.CLIENT_ID = c.CLIENT_ID
AND a.SITE_ID= c.SITE_ID
AND a.SITE_NAME= c.SITE_NAME
UNION ALL
SELECT
b.CLIENT_NAME, b.SITE_NO, b.SITE_NAME,
c.FILTER_1, c.FILTER_2,
b.MANAGER, b.AUDIT_DATE, b.THIS_AUDIT_SCORE,
b.ALERTS_FLAG, b.REPEAT_FLAG, b.ACTION_PLAN_FLAG,
b.Cash, b.Revenue, b.Stock, b.[Unaccounted Stock],
b.[People & Payroll], b.[Safe], b.[Security],
b.[Petty Cash], b.[Tills], b.[Bankings], b.[Sales],
b.[Vouchers & Discounting], b.[PDQ], b.[Administration],
b.[Stock Verification], b.[Stock Management], b.[Ordering]
FROM
MMA_AUDITSUM_STG_35 As b
INNER JOIN
MMA_SITE_MST As c ON b.CLIENT_ID = b.CLIENT_ID
AND b.SITE_ID = c.SITE_ID
AND b.SITE_NAME = c.SITE_NAME
任何观点都欢迎,因为我还在学习,所以不确定我是否做了上述权利,即使它能得到我需要的结果:)
提前谢谢
约翰
答案 0 :(得分:1)
如果确实需要所有单独的表,您可以考虑创建一个视图:
CREATE VIEW v_MMA_AuditSum(
SELECT * FROM MMA_AUDITSUM_STG_34
UNION ALL
SELECT * FROM MMA_AUDITSUM_STG_35
UNION ALL
....
)
然后将其加入您的MMA_SITE_MST
SELECT a.CLIENT_NAME
,a.SITE_NO
,a.SITE_NAME
,a.FILTER_1
,a.FILTER_2
,b.*
FROM MMA_SITE_MST AS a
JOIN cte AS b ON a.CLIENT_ID= b.CLIENT_ID
AND a.SITE_ID= b.SITE_ID
AND a.SITE_NAME= b.SITE_NAME