如何展示' 0'如果该月份的表中没有数据,则为一个月的金额

时间:2015-11-01 16:50:28

标签: sql-server tsql

我有两个表Costtable(Id,ResourceId,Amount,Date)和  ResourceTable(ResourceId,Name),显示如下输出。

enter image description here

我希望在9月的情况下显示其余名称的0金额。对于例如如果资源的其余部分未出现在成本表中,则它们应显示为金额

我想要的输出

enter image description here

我当前的查询

SELECT
    RG.Id AS Id,
    RG.Name AS Name,
    ISNULL(SUM(AC.Amount), 0) AS Amount,
    RIGHT(CONVERT(varchar(10), AC.[Date], 105), 7) AS [YearMonth]
FROM 
    Cost AS AC
    INNER JOIN Resource AS RG ON AC.ResourceGroupId = RG.Id
WHERE 
    AC.PortalId = '100' AND 
    [Date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(m, -11, GETDATE())), 0)
GROUP BY 
    RG.Name, 
    RG.Id, 
    RIGHT(CONVERT(varchar(10), AC.[Date], 105), 7)
ORDER BY 
    RG.Name DESC

2 个答案:

答案 0 :(得分:0)

您可以使用cross joinleft join执行此操作。您的问题很难理解,因为您的表格和说明不同。但是,这就是这个想法:

select t.minid, t.name, ym.yearmonth, coalesce(amount, 0) as amount
from (select name, min(id) as minid from t group by name) n cross join
     (select distinct yearmonth from t) ym left join
     t
     on t.name = n.name and t.yearmonth = ym.yearmonth;

答案 1 :(得分:0)

只做一个FULL JOIN而不是一个innerjoin。

这应该可以解决问题。