我有一個表叫銷售:累計總和與百分比
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
我需要的是得到total
列,合計(總)的總和時,狀態爲活動和繁殖它的X個(我可以這樣做),因爲我必須選擇他們的總額(所有票的總和)的所有門票是<= sum(total) * x percentage
並將其複製到另一個表(相同的值)
因此,如果我有票的總和101 = 90,並且票據102的總和= 60,票據103的總和= 15,並且總和(總數)* x百分比= 160,查詢將僅返回來自門票101和102
所有早讀我發現,不知何故確實有點像我所需要的,但使用id_Sales而不是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
我espect到收到的是:
id_sale id_ticket total state
------- --------- ----- -----
101 101 30 active
102 101 60 active
103 102 30 active
104 102 30 active
在至極票101和票的總和102是< =總和(總)* X
所以101和102 = 150和求和的總和(總)* X = 160(例如)
我該如何做我所需要的,或者如何編輯這段代碼,使它符合我的要求。
感謝您發佈樣本數據,但可以發佈您需要的預期結果樣本嗎? – Taryn 2012-07-23 19:36:07
我希望我可以+10 @ bluefeet的評論。您嘗試的查詢很高興知道,但我們大多數人寧願知道您實際期望的結果。 – 2012-07-23 19:40:02
如何選擇第二步(您想要達到160但未超過)票號asc的訂單? – Hogan 2012-07-23 19:40:46