I have the below query which derives 'returns order' by productcode
SELECT ProductCode, producttitle, COUNT(ProductCode)as Unitsreturned
FROM [tbl_OrderItem]
where
(DateReturnAccepted between '2017-07-09 00:00:00.00' and '2017-07-15 23:59:59.99')
group by ProductCode,producttitle
order by COUNT(ProductCode) desc
I want to include corresponding sale for that product using datecreated column
Below query will retrive total sale for each product.But i want to merge these queries together?
select ProductCode, COUNT (productcode) FROM [tbl_OrderItem]
where (DateCreated between '2017-07-09 00:00:00.00' and '2017-07-15 23:59:59.99')
and NumberDespatched = '1'
group by ProductCode
order by COUNT(ProductCode) desc
Output column i need is ProductCode, producttitle, Unitsreturned, Unitssold
You can wrap each query into a cte and then join the two cte's, something like this:
;with returns as
( -- your first query here with no order by clause),
Dispached as
( -- your second query here with no order by clause)
select
*
from returns r full join Dispatched d on
d.productcode = r.productcode.
Another option, is as follows, which is preferable because you are scanning the data only once
SELECT ProductCode,
producttitle,
SUM( CASE WHEN
DateCreated >= '20170709'
AND DateCreated < '20170716'
AND NumberDespatched=1 THEN 1
ELSE 0 END) AS UnitsCreated,
SUM( CASE WHEN
DateReturnAccepted >= '20170709'
AND DateReturnAccepted < '20170716' THEN 1
ELSE 0 END) Unitsreturned
FROM
[tbl_OrderItem]
GROUP BY
ProductCode ,
producttitle
ORDER BY
UnitsCreated DESC,
Unitsreturned DESC;
In either case, use the date range as I have shown here with a >= and < rather than trying to use the between clause as you have done with time parts etc.