Invoice days and amount with Distinct Value I am having a billing table like as above.

I need to get a billing age wise report by using distinct of Branch, UserId, Customer, BillType.

I need to wirte a Stored procedure for getting the following result.

How to write a query for this
You'll want to check out the datediff function, see below example.

select branch, 
       userid,
       customer,
       billtype,
       case when datediff(d,billdate,getdate()) &gt;= 0 and datediff(d,billdate,getdate()) &lt;= 30 then billingamount else 0 end [0 - 30 days],
       case when datediff(d,billdate,getdate()) &gt;= 31 and datediff(d,billdate,getdate()) &lt;= 60 then billingamount else 0 end [31 - 60 days],
       case when datediff(d,billdate,getdate()) &gt;= 61 and datediff(d,billdate,getdate()) &lt;= 90 then billingamount else 0 end [61 - 90 days],
       case when datediff(d,billdate,getdate()) &gt;= 91 and datediff(d,billdate,getdate()) &lt;= 120 then billingamount else 0 end [91 - 120 days],
       case when datediff(d,billdate,getdate()) &gt;= 121 then billingamount else 0 end [121+ days],
       billingamount as total
  from #test