Tuesday, May 2, 2023

How to show no of items per every hour

### Following SQL Query used to report Hourly items and repot details of last n hour(s) data


```SQL

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 

Declare @FromPastXhour int=1

/*Common Table Expression */
;
With cte As(

Select Item

Select S.Product_id, p.Name, isnull(s.Quantity,0), isnull(s.Price,0.00) ,
(isnull(s.Quantity,0)* isnull(s.Price,0.00) ) as Total, 
dateadd(hh,datediff(hh,'20010101',s.SaleDateTime),'20010101') as Hourly 

from Product p
join Sale s on p.id = s.product_id
and s.SaleDateTime >= Cast(GetDate() as Date)

)

Select * into #list from cte 

/*No of product items per hour */
Select Hourly, Name from #list group by [Hourly],[Name] order by 1


/*product and sales details since last x hour(s)*/
select * from #list where SaleDateTime> DateAdd(hh,-1*@FromPastXhour,Getdate()) 


/*Reporting on all days*/

select cast(SaleDateTime as date),  total
from Sale (nolock)
group by  cast(SaleDateTime as date)
order by 1;


if  Object_ID('tempdb..#list') is not null 
Drop table #list

```

No comments:

Post a Comment