我知道这对SQL使用者来说很简单,但是我试图将两个简单的查询合并为一个。从代码中可以明显看出job.ActiveJob.ID = job.EstimateTbl.ID_Job。
我正在尝试获取:id,JobName,sum(itemAmount)
感谢您的帮助。
SELECT a.id, a.JobName
FROM job.ActiveJobsTbl AS a
WHERE a.ID = '100'
SELECT SUM(itemAmount)
FROM job.EstimateTbl
WHERE ID_Job = '100'
答案 0 :(得分:5)
您可以JOIN
来ON E.ID_Job = A.ID
的表,并使用SELECT
来获取GROUP BY
中的值
SELECT A.id, A.JobName, SUM(E.itemAmount) AS Amount
FROM job.ActiveJobsTbl AS A
INNER JOIN job.EstimateTbl E ON E.ID_Job = A.ID
WHERE A.ID = '100'
GROUP BY A.id, A.JobName;
答案 1 :(得分:1)
使用LEFT JOIN
SELECT a.id, a.JobName,EstimateTbl.itemAmount
FROM job.ActiveJobsTbl AS a
left join
(
SELECT SUM(itemAmount) itemAmount,ID_Job
FROM job.EstimateTbl
group by ID_Job
) EstimateTbl on EstimateTbl.ID_Job = a.ID
WHERE a.ID = '100'
答案 2 :(得分:0)
您可以使用APPLY
:
select a.id, a.JobName, t.itemAmount
from job.ActiveJobsTbl AS a OUTER APPLY
(SELECT SUM(t.itemAmount) AS itemAmount
FROM job.EstimateTbl AS t
WHERE t.ID_Job = a.ID
) t
WHERE a.ID = 100;
答案 3 :(得分:0)
尝试一下:
SELECT A.id, A.JobName, SUM(E.itemAmount) AS Amount
FROM job.ActiveJobsTbl AS A
INNER JOIN job.EstimateTbl E ON E.ID_Job = A.ID
WHERE A.ID = '100'
GROUP BY A.id, A.JobName;