我有这张桌子
select * from points
+---------+------+------+
| NAME | Type | RANK |
+---------+------+------+
| A | H | 90 |
| A | M | 100 |
| A | H | N/A |
| A | H | N/A |
| A | H | N/A |
| B | H | 100 |
| B | M | 100 |
| B | L | 100 |
| C | H | 85 |
| C | M | 100 |
+---------+------+------+
我正在使用此查询
SELECT name,
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 90 * `# of active H` / `# of H` + 20 * `# of active L` / `# of L`
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,
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
) t
ORDER
BY name
;
我得到此输出
+---------+-------+
| NAME | SCORE |
+---------+-------+
| A | 60 | <--[(2xH)=40 + (1xM)=20] =60
| B | 100 | <--[(1xH)=70 + (1xM)=20 + (1xL)=10] =100
| C | 100 | <--[(1xH)=80 + (1xM)=20] =100
+---------+-------+
我需要这个所需的输出
+---------+-------+
| NAME | SCORE |
+---------+-------+
| A | 36 | <--[70/4=(17.5 per H) therefore (17.5)*(rank of that h: 90%)=15.75 + (M values, which equals 20/1 =20 Therefore: rank of that m:100% * 20 = 100) = 36 rounded
| B | 100 | <--[(1xH)=70 + (1xM)=20 + (1xL)=10] =100
| C | 88 | <--[(1xH)=80 + (1xM)=20] =100
+---------+-------+
需要进行计算:
当所有值都存在时,它们的评分如下:
H = 70 M = 20 L = 10
如果某个名称有多种类型(H,M或L),则分配如下:
H /(H的数量); M /(M的数量); L /(L的数量)
- 示例:A具有4 H,因此每个H
70/4 = 17.5但有些名字有一套完整的设置,没有所有'类型。 - 示例:C具有类型值:'H&amp; M` only
现在,对于C,类型'H'和'M'必须等于100.
因此,当只有'H`和'M'出现时,它们的评分如下:
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 :(得分:1)
这看起来很熟悉。 : - )
您的描述在许多地方都不一致 - 例如,您的&#34;期望的输出&#34; A
使用70
和20
即使A
没有类型L
- 但如果你的意思是我的意思,那么主要变化您需要将SUM(IF(rank AND type = 'H', 1, 0)) AS `# of active H`
更改为SUM(IF(type = 'H', rank / 100.0, 0)) AS `rank of H`
(同样适用于M
和L
),并更改对`# of active H`
的所有引用以引用`rank of H`
而是。这样每条记录将按其排名的比例包含在内,而不是一个全有或全无的东西。
在将CAST
转换为整数时,您还希望使用ROUND
代替CAST
- 或score
-