簡體   English   中英

MySQL減去兩行相似的行並將結果乘以另一行

[英]MySQL subtract two similar rows and multiply results by another row

我希望能夠從相同區域,類型和os中減去要保留的按需數量,然后將剩余數量乘以比率。

這是mysql數據的示例轉儲

| Zone  | Type  | Qty | OS    | Reservation | Rate  |
| zone1 | type1 | 12  | linux | ondemand    | 0.24  |
| zone1 | type1 | 6   | linux | reserved    | 0.056 |
| zone1 | type2 | 3   | linux | ondemand    | 0.82  |
| zone2 | type1 | 5   | mswin | ondemand    | 0.24  |
| zone2 | type1 | 2   | mswin | reserved    | 0.056 |
| zone2 | type2 | 3   | linux | ondemand    | 0.82  |
| zone3 | type1 | 4   | linux | ondemand    | 0.24  |
| zone3 | type1 | 1   | linux | reserved    | 0.056 |

結果將是

| Zone  | Type  | Qty | OS    | Reservation | Rate  | sum() |
| zone1 | type1 | 6   | linux | ondemand    | 0.24  | 1.44  |
| zone1 | type1 | 6   | linux | reserved    | 0.056 | 0.336 |
| zone1 | type2 | 3   | linux | ondemand    | 0.82  | 0.246 |
| zone2 | type1 | 3   | mswin | ondemand    | 0.24  | 0.72  |
| zone2 | type1 | 2   | mswin | reserved    | 0.056 | 0.112 |
| zone2 | type2 | 3   | linux | ondemand    | 0.82  | 0.246 |
| zone3 | type1 | 3   | linux | ondemand    | 0.24  | 0.72  |
| zone3 | type1 | 1   | linux | reserved    | 0.056 | 0.056 |

我不確定如何獲得明確的聲明來解決這個問題。 我不知道這在mysql中是否可行,或者是否需要編寫腳本然后生成輸出。 任何幫助表示贊賞。

該區域中並不總是為包含ondemand的類型和os保留相應的內容。

您需要將表連接到自身:

select
    t1.Zone, t1.Type, t1.Qty - ifnull(t2.Qty, 0), t1.OS,
    t1.rate, (t1.Qty - ifnull(t2.Qty, 0)) * t1.rate as total
from mytable t1
left join mytable t2
    on t1.zone = t2.zone
    and t1.type = t2.type
    and t1.os = t2.os
    and t2.reservation = 'reserved'

和t1.reservation ='ondemand'

關鍵功夫是加入條件中的最后一個條件。 它確保“ ondemand”行只有一個聯接-帶有left join聯接時,所有其他行類型(以及那些沒有相應“ reserved”行的“ ondenand”行)對於該聯接的qty值將為空(因此ifnull()為它們提供零。

請注意,即使“按需”行沒有匹配的“保留”行,這也將正確計算總數。

老實說,我以前從未見過這種查詢,在這種查詢中,只有來自父側的一些行被連接到了,而所有行都被保留了。

這還沒有運行,但是也許是這樣?

select zone, type, os, ondemand_cnt, reserved_cnt, ondemand_cnt-reserved_cnt as cnt, 
<some_rate>*(ondemand_cnt-reserved_cnt) as calc_rate
from
(
select zone, type, os, sum(qty) as ondemand_cnt 
from table
where reservation = 'ondemand'
group by zone, type, os
) as o
join
(
select zone, type, os, sum(qty) as reserved_cnt
from table
where reservation = 'reserved'
group by zone, type, os
) as r on (o.zone = r.zone and o.type = r.type and o.os = r.os)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM