How to break sales query results by day

211 views Asked by At

I have a sales query by date range, where the date range is defined by user input. I would like to divide the results by day. i.e.: say the user input the date range from 01/01/16 - 01/15/16, I would like the break the results for each day. I'm using DATENAME(DD,T1.[DocDate]) to break it, and it is kind of working, but the results are no accurate. I figure I have to use the same break in the Returns subquery. Please see the full query below:

Thank you

SELECT
'2016' as 'Year',
t4.remarks as 'Department',
DATENAME(DD,T1.[DocDate]) as 'Day',
sum(t0.[quantity])-(ISNULL(p.quantity,0)) as 'Quantity',
sum(t0.linetotal - t0.linetotal*t1.discprcnt/100)-(ISNULL(p.total,0)) as 'Total',
sum(T0.[GrssProfit])-(ISNULL(p.profit,0)) as 'Profit $',
(sum(T0.[GrssProfit])-(ISNULL(p.profit,0)))/(sum(t0.linetotal - t0.linetotal*t1.discprcnt/100)-(ISNULL(p.total,0)))*100 as 'Profit%'

FROM INV1 T0 with (nolock)
INNER JOIN OINV T1 with (nolock) on t0.docentry = t1.docnum
INNER JOIN OSLP T2 with (nolock) on t0.SlpCode = t2.SlpCode 
LEFT JOIN OHEM T3 with (nolock) on t0.slpcode = t3.SalesPrson 
LEFT JOIN OUDP T4 with (nolock)  on t3.dept = t4.Code

--BEGINS QUERY FOR THE RETURNS-- 
left join (select t9.name as 'dept',sum(t5.quantity) as 'quantity',sum(t5.linetotal - t5.linetotal*t6.discprcnt/100) as 'total',sum(t5.grssprofit) as 'profit'
from [dbo].[rin1] t5 with (nolock)
inner join orin t6 with (nolock) on t5.docentry = t6.docentry
INNER JOIN OSLP T7 with (nolock) on t5.SlpCode = t7.SlpCode 
LEFT JOIN OHEM T8 with (nolock) on t5.slpcode = t8.SalesPrson 
LEFT JOIN OUDP T9 with (nolock) on t8.dept = t9.Code
INNER JOIN OITM T10 with (nolock) on t5.itemcode = t10.itemcode
where t5.docdate between '[%1]' and '[%2]' and t10.invntitem = 'Y'
and (t5.linetotal - (t5.linetotal*t6.discprcnt/100)) <> '0'
group by t9.name) p on p.dept = t4.name
--ENDS QUERY FOR THE RETURNS-- 

WHERE t1.docdate between '[%1]' and '[%2]'
and t4.remarks is not null
and t4.remarks = 'perfume provider'
and (t0.linetotal - (t0.linetotal*t1.discprcnt/100)) <> '0'

group by DATENAME(DD,T1.[DocDate]),t4.remarks,p.quantity,p.total,p.profit
1

There are 1 answers

3
Overhed On

Instead of a sub-query for your returns (with the same kind of group by as your Invoices query), you should use a UNION instead. Your Group-By is fine, but like you mentioned, your subquery is going to result in bad data.

Any time you have distinct "starting points" for your data, a Union is the way to go.