I have a table called Sales:
id_sale id_ticket total state
------- --------- ----- -----
100 100 30 inactive
101 101 30 active
102 101 60 active
103 102 30 active
104 102 30 active
105 103 10 active
106 103 5 active
What I need is to get the total sum of the total column, sum(total) when the state is active and multiply it for x percentage (I can do that), having that I have to select all the tickets that their sum (of all the tickets summed) is <= sum(total) * x percentage and copy it to another table (same values)
So if I have the sum of ticket 101 = 90 and the sum of ticket 102 = 60 and the sum of ticket 103 = 15, and the sum(total)*x percentage = 160, the query will only return all the info from the tickets 101 and 102.
Reading all morning I found a code that somehow does something like what I need but using id_Sales and not id_ticket:
select t1.id_sale, t1.total, SUM(t2.total) as sum
from sales t1
inner join sales t2 on t1.id_sale >= t2.id_sale
where t2.state='active'
group by t1.id_sale, t1.total
having sum(t2.total)<=(
select sum(total)*.65
from sales
where state='active')
order by t1.id_sale
What i espect to recieve is:
id_sale id_ticket total state
------- --------- ----- -----
101 101 30 active
102 101 60 active
103 102 30 active
104 102 30 active
In wich the sum of ticket 101 and ticket 102 is <= sum(total)*x
so the sum of 101 and 102 = 150 and sum(total)*x = 160 (for example)
How can I do what I need or how can I edit this code so it does what I’m looking for.
You could start with something like this:
The first CTE,
grouped_and_ranked, retrieves active sales and calculates totals by ticket as well as the grand total (using windowedSUM()). It also assigns ranking numbers to the tickets to be used later when calculating the running total.The next CTE,
cumulative, is a recursive CTE. It retrieves rows from the previous result set as long as the running total is no greater than the specified@percent‘age of the grand total.The main SELECT uses the final ticket list to get the detail rows, by joining the list back to the
salestable.This query can be tested at SQL Fiddle.