简化查询 SQL
Simplify Query SQL
我有这样的查询:
--FIRST QUERY
SELECT a.EmployeeId, a.Seq, a.EmployeeAddress
INTO #Address
FROM Address a
WHERE a.Seq = 1
--SECOND QUERY
SELECT a.EmployeeId, a.PayrollType, SUM(a.Amount) Amount
INTO #Payroll
FROM Payroll a
WHERE a.PayrollType = 'THR'
GROUP BY a.EmployeeId, a.PayrollType
--RESULT
SELECT a.EmployeeId, a.EmployeeName, b.ReligionName,
ISNULL(c.EmployeeAddress, '-') EmployeeAddress, ISNULL(d.Amount,0) Amount
FROM Employee a
INNER JOIN Religion b ON a.ReligionId = b.ReligionId
LEFT JOIN #Address c ON a.EmployeeId = c.EmployeeId
LEFT JOIN #Payroll d ON a.EmployeeId = d.EmployeeId
这是我的截图table:
结果正是我需要的。但是,我很好奇是否有另一种方法可以简化查询。有什么想法吗?
谢谢。
您只能使用 1 个查询而不是使用临时表
--RESULT
SELECT a.EmployeeId, a.EmployeeName, b.ReligionName,
ISNULL(c.EmployeeAddress, '-') EmployeeAddress, SUM(ISNULL(d.Amount,0)) Amount
FROM Employee a
INNER JOIN Religion b ON a.ReligionId = b.ReligionId
LEFT JOIN Address c ON a.EmployeeId = c.EmployeeId and c.Seq = 1
LEFT JOIN Payroll d ON a.EmployeeId = d.EmployeeId and d.PayrollType = 'THR'
GROUP BY a.EmployeeId, a.EmployeeName, b.ReligionName, c.EmployeeAddress
我有这样的查询:
--FIRST QUERY
SELECT a.EmployeeId, a.Seq, a.EmployeeAddress
INTO #Address
FROM Address a
WHERE a.Seq = 1
--SECOND QUERY
SELECT a.EmployeeId, a.PayrollType, SUM(a.Amount) Amount
INTO #Payroll
FROM Payroll a
WHERE a.PayrollType = 'THR'
GROUP BY a.EmployeeId, a.PayrollType
--RESULT
SELECT a.EmployeeId, a.EmployeeName, b.ReligionName,
ISNULL(c.EmployeeAddress, '-') EmployeeAddress, ISNULL(d.Amount,0) Amount
FROM Employee a
INNER JOIN Religion b ON a.ReligionId = b.ReligionId
LEFT JOIN #Address c ON a.EmployeeId = c.EmployeeId
LEFT JOIN #Payroll d ON a.EmployeeId = d.EmployeeId
这是我的截图table:
结果正是我需要的。但是,我很好奇是否有另一种方法可以简化查询。有什么想法吗?
谢谢。
您只能使用 1 个查询而不是使用临时表
--RESULT
SELECT a.EmployeeId, a.EmployeeName, b.ReligionName,
ISNULL(c.EmployeeAddress, '-') EmployeeAddress, SUM(ISNULL(d.Amount,0)) Amount
FROM Employee a
INNER JOIN Religion b ON a.ReligionId = b.ReligionId
LEFT JOIN Address c ON a.EmployeeId = c.EmployeeId and c.Seq = 1
LEFT JOIN Payroll d ON a.EmployeeId = d.EmployeeId and d.PayrollType = 'THR'
GROUP BY a.EmployeeId, a.EmployeeName, b.ReligionName, c.EmployeeAddress