This is my input data from a table in db: enter image description here I want to get below information as output: enter image description here
If you observe the output I need to get distinct serial number count for a model from day 1 to till date. for ex: for day1: count(distinct serialnumber) as sold day2 : count(distinct serialnumber from day1) as sold I did this using cumulative sales but because of some serial numbers has multiple sales on different dates, I'm getting a wrong count. Can anyone please help me with T-SQL query for this request?
You could do this with two levels of aggregation:
select model, sale_date,
sum(count(*)) over(partition by model order by sale_date) sale_qty
from (
select model, serial_number, min(sale_date) sale_date
from mytable
group by model, serial_number
) t
group by model, sale_date
order by model, sale_date
With this technique, each serial_number
is counted only once, on its first appearance date.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.