我有下表:
select * from points
+---------+-------------------+------+------+
| NAME | TITLE | Type | RANK |
+---------+-------------------+------+------+
| A | Hippo | H | 1 |
| A | Hippo | M | 1 |
| A | Hippo | H | N/A |
| A | Hippo | H | 1 |
| A | Hippo | H | N/A |
| B | Snail | H | 1 |
| B | Snail | M | 1 |
| B | Snail | L | 1 |
| C | Dog | H | 1 |
| C | Dog | M | 1 |
+---------+-------------------+------+------+
所需的输出
+---------+----------+-------+
| NAME | TITLE | SCORE |
+---------+----------+-------+
| A | Hippo | 60 | <--[(2xH)=40 + (1xM)=20] =60
| B | Snail | 100 | <--[(1xH)=70 + (1xM)=20 + (1xL)=10] =100
| C | Dog | 100 | <--This should happen because [(1xH)=80 + (1xM)=20] =100
+---------+----------+-------+
需要进行计算:
当所有值都存在时,它们的评分如下:
H = 70 M = 20 L = 10
如果某个名称有多种类型(H,M或L),则分配如下:
H /(H的数量); M /(M的数量); L /(L的数量)= 100
- 示例:A具有4 H,因此每个H
70/4 = 17.5但有些名字有一套完整的设置,没有所有'类型。 - 示例:C具有类型值:'H&amp; M` only
H = 80 M = 20
M = 60 L = 40
H = 90 L = 10
还
如果只有H是presnet H = 100
如果只有M是presnet M = 100
如果只有L是presnet L = 100
答案 0 :(得分:2)
如果我理解正确,这就是你想要的:
SELECT name,
title,
CAST(
( -- only have H, or only have M, or only have L:
CASE WHEN `# of H` = 0 AND `# of M` = 0 THEN 100 * `# of active L` / `# of L`
WHEN `# of H` = 0 AND `# of L` = 0 THEN 100 * `# of active M` / `# of M`
WHEN `# of M` = 0 AND `# of L` = 0 THEN 100 * `# of active H` / `# of H`
-- only have H & M, or only have H & L, or only have M & L:
WHEN `# of H` = 0 THEN 60 * `# of active M` / `# of M` + 40 * `# of active L` / `# of L`
WHEN `# of M` = 0 THEN 0 -- ??????????
WHEN `# of L` = 0 THEN 80 * `# of active H` / `# of H` + 20 * `# of active M` / `# of M`
-- have all three:
ELSE 70 * `# of active H` / `# of H` + 20 * `# of active M` / `# of M` + 10 * `# of active L` / `# of L`
END
) AS SIGNED ) AS score
FROM ( SELECT name,
title,
SUM(IF( type = 'H', 1, 0)) AS `# of H`,
SUM(IF(rank AND type = 'H', 1, 0)) AS `# of active H`,
SUM(IF( type = 'M', 1, 0)) AS `# of M`,
SUM(IF(rank AND type = 'M', 1, 0)) AS `# of active M`,
SUM(IF( type = 'L', 1, 0)) AS `# of L`,
SUM(IF(rank AND type = 'L', 1, 0)) AS `# of active L`
FROM points
GROUP
BY name,
title
) t
ORDER
BY name
;