left join以获取第二个表

时间:2015-10-07 09:46:17

标签: sql-server sql-server-2008

如果所有Collection.Amount的条目都没有,只有那些JId有一些付款的条目

,如何从表格集中获取JId的总和
ALTER PROCEDURE dbo.test
AS
select JobCard.JId, sum(cast(isnull(Collection.Amount, 0) as bigint)) as [Amount] 
from JobCard left join Collection on JobCard.JId=Collection.JId 
group by JobCard.JId, Collection.Amount 
order by JobCard.JId

2 个答案:

答案 0 :(得分:2)

我认为你应该像这样编写你的查询,这会给你完美的结果。

    ALTER PROCEDURE dbo.test
AS
    SELECT J.JId,
           SUM(CAST(ISNULL(C.Amount, 0) AS BIGINT)) AS [Amount]
    FROM   JobCard J
           LEFT JOIN COLLECTION C
                ON  J.JId = C.JId
    GROUP BY
           J.JId
    ORDER BY
           J.JId

需要从group by子句中删除Collection.Amount。

答案 1 :(得分:1)

将您的GROUP BY条款更改为:

group by JobCard.JId