Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Two count sql queries

Author  Topic 

ketangarg86
Starting Member

3 Posts

Posted - 2015-03-12 : 11:14:23
Hi,

I have a requirement to calculate the % change in the number of orders received today with the number of orders that were received 3 days back. All data is in the same table. There is a received date column.

I have two count(*) queries - one for today and one for 3 days back running separately and getting the results. Is it possible I can get the % change in orders received from 3 days back and today in one query.

Also if I want to get the number of orders received today between 12:00am today and current time. How would I modify the query.

Please help. I am relatively new to Oracle SQL.

Thanks
Ketan

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2015-03-12 : 16:56:53
You can use the lag function - something like this:
select
date,
count(orderid),
lag(count(orderid),3,null) over(order by date)
from
tbl
group by
date;
If you have dates on which there are no orders, you would need to use a calendar table and left join to that calendar table.

For today's orders, if you want to consider only time upto the current time, add a where clause like
where
date <= getdate()
Does your system enter future orders with a future timestamp? If not, the where clause is redundant.
Go to Top of Page

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2015-03-12 : 17:20:25
In mssql I would write something like:
select sum(case when received_date>=cast(getdate() as date) then 1 else 0 end) as today_count
,sum(case when received_date>=dateadd(hh,12,cast(getdate() as date)) then 1 else 0 end) as today_noon_count
,sum(case when received_date>=cast(getdate() as date) then 0 else 1 end) as three_days_ago_count
from yourtable
where received_date>=cast(getdate() as date)
or (received_date>=dateadd(dd,-3,cast(getdate() as date))
and received_date<dateadd(dd,-2,cast(getdate() as date))
)
Go to Top of Page
   

- Advertisement -