我有以下两个 Select 语句-
SELECT *
FROM tblAllocations
WHERE AllocID IN
(
SELECT MAX(AllocID)
FROM tblAllocations
WHERE FeeEarner = 'KLW' AND [Date] <= '2013-12-31'
GROUP BY FeeEarner, CaseNo
和
SELECT UserID, CaseNo, SUM(Fees) AS [Fees]
FROM tblTimesheetEntries
WHERE UserID = 'KLW' AND [Date] <= '2013-12-31'
GROUP BY UserID, CaseNo
返回以下结果 -
我想要的是将它们组合在一个 Select 语句中,该语句从第一个查询中提取一些字段,从第二个查询中提取其他字段。根据上面的结果,应该只返回 5 行,其中 3 行将包含来自两个 Query 的字段,2 个将只有来自一个 Query 的字段(因此它会有一些 NULL 值)
我尝试了以下 -
SELECT q1.CaseNo, q1.FeeEarner,
q2.Fees AS [Fees],
q1.Fees AS [Billed],
(q2.Fees - q1.Fees) AS WIP
FROM
(
SELECT *
FROM tblAllocations
WHERE AllocID IN
(
SELECT MAX(AllocID)
FROM tblAllocations
WHERE FeeEarner = 'KLW'
AND [Date] <= '2013-12-31'
GROUP BY FeeEarner, CaseNo
)
) AS q1,
(
SELECT UserID, CaseNo, SUM(Fees) AS [Fees]
FROM tblTimesheetEntries
WHERE UserID = 'KLW'
AND [Date] <= '2013-12-31'
GROUP BY UserID, CaseNo
) AS q2
然而,这就像一个交叉连接,并给了我 15 行如下 -
有人可以建议我如何正确组合这两个查询以便只返回 5 行。