SSRS SQL Query to show the zero value for non existing records

我的未来我决定 提交于 2019-12-12 01:38:14

问题


I am using the following query to pull the data for last 11/12 months

SELECT [ID]
      ,[Name]  
      ,[Amount]     
FROM DB1 
WHERE [Period] BETWEEN @FromMonth AND @ToMonth  
      AND [Desc] = 'XYZ'  

What I want to achieve is, some IDs does not have a any record for some periods(month) with no amount. Currently the query doesn't return anything for those combination of names and months where there is no record in DB. It only displays a result if the ID has a certain amount and date in db. However, what I want is that if an ID doesn't have an amount for a month then it should show the amount for that month.

@FromMonth and @ToMonth are the parameters being passed to the report. I know I can achieve this by pivoting but I don't want to do that. Any hints?


回答1:


If I had to guess based on your title, perhaps this is what you're looking for using a case statement:

select id, name, 
    case when Period between @FromMonth and ToMonth and [Desc] = 'XYZ' 
         then amount 
         else 0 
    end as amount
from db1

This will return all ids and names from db1, but only include the amount for those records matching your previous where criteria.


By the way, I'd typically recommend avoid using reserved words as column names (desc).



来源:https://stackoverflow.com/questions/39030451/ssrs-sql-query-to-show-the-zero-value-for-non-existing-records

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!