MySQL 减去两个相似的行并将结果乘以另一行

标签 mysql sum distinct

我希望能够从同一区域、类型和操作系统中减去按需预留的数量,然后将剩余数量乘以费率。

这是一个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 是否可行,或者我是否需要编写脚本然后生成输出。任何帮助表示赞赏。

对于包含按需的类型和操作系统,在区域中并不总是有相应的保留。

最佳答案

您需要将表连接到自身:

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'

Ihe critical kung fu 是加入条件中的最后一个条件。它确保只有“ondemand”行的连接 - 使用 left join,所有其他行类型(以及那些没有相应“reserved”行的“ondenand”行)将为有加入数量值(因此 ifnull() 给他们一个零来使用)。

请注意,即使“按需”行没有匹配的“保留”行,这也会正确计算总数。

老实说,我以前从未见过这种查询,其中只有来自父端的一些行被连接到,但是所有行被保留.

关于MySQL 减去两个相似的行并将结果乘以另一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804426/

相关文章:

python - 求和函数如何在带有for循环的python中工作

mysql - 不要抓取重复项(MYSQL DISTINCT GROUP BY)

mysql - SQL:查找行之间的差异

php - 在黑莓上运行 apache、php 和 mysql

mysql - 限制 MySQL 中的不同值

mysql连接2个表,第二个表需要SUM()

tsql - 与正常的行集相比,FOR XML AUTO 子句能否给出意想不到的结果?

mysql - JPA Criteria 查询在子查询中包含多列

php - 我如何更改此脚本,以便当它发现用户存在于 MySQL 数据库中时它会更新并且不返回错误消息?

ruby-on-rails-3 - Rails中的关联模型和SUM查询