Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...