假设我有以下数据:
object size color units
------ ---- ----- -----
ball small red 3
ball small red 2
ball medium blue 2
ball medium blue 1
ball big yellow 2
hat big green 3
hat big green 4
umbrella medium blue 1
umbrella medium blue 4
umbrella big blue 4
umbrella huge red 2
umbrella huge green 1
book small white 4
book small brown 3
book medium brown 2
我需要一个查询,该查询返回所有对象的所有对象颜色大小变化,对于该对象,该大小和颜色的变化总单位中至少有一个至少为5,因此该查询将返回以下行:
object size color total_units
------ ---- ----- ------
ball small red 5
ball medium blue 3
ball big yellow 2
umbrella medium blue 5
umbrella big blue 4
umbrella huge red 2
umbrella huge green 1
之所以出现所有球及其每个尺寸-颜色变化的总数,是因为至少存在2个不同的球,并且其中至少一个球的总单位为5个或更多
之所以在结果中显示所有伞及其每个大小-颜色变化的总数,是因为至少有2种不同的伞,且其中至少一把伞的总单位为5个或更多
帽子没有出现在结果中的原因是,即使大绿色帽子超过5个(7),也没有至少2个不同的帽子
之所以没有一本书出现在结果中是因为即使有3本不同的书,但其中至少没有5本书。
感谢您向我展示了如何实现这一目标!
答案 0 :(得分:1)
使用窗口函数(在最新版本的MySQL和MariaDB数据库中),这很容易:
MEMORY {
flash (rx) : ORIGIN = DEFINED(bootloaderSymbol) ? 0x00000000 : 0x00004000, LENGTH = DEFINED(bootloaderSymbol) ? 112K : 16K
ram (rwx) : ORIGIN = 0x1FFFF000, LENGTH = 16K
}
答案 1 :(得分:1)
Object
值,该值至少具有1个以上的组合,并且其中一个组合至少具有5个单位。GROUP BY
)。查询
SELECT
t.object, t.size, t.color, SUM(t.units) AS total_units
FROM
your_table AS t
JOIN
(
SELECT dt.object
FROM
(
SELECT
object, size, color, SUM(units) AS total_units
FROM your_table
GROUP BY
object, size, color
) AS dt
GROUP BY dt.object
HAVING COUNT(*) > 1 AND
SUM(dt.total_units >= 5) /* atleast one with 5 units */
) AS dt2
ON dt2.object = t.object
GROUP BY t.object, t.size, t.color;
结果
| object | size | color | total_units |
| -------- | ------ | ------ | ----------- |
| ball | big | yellow | 2 |
| ball | medium | blue | 3 |
| ball | small | red | 5 |
| umbrella | big | blue | 4 |
| umbrella | huge | green | 1 |
| umbrella | huge | red | 2 |
| umbrella | medium | blue | 5 |