我需要获取devicePoint,osPoint,browserPoint的总和,这是使用SELECT中的case语句填充的。这是我的代码
SELECT *,
CASE
WHEN device='Default' THEN 1
ELSE 5
END AS devicePoint,
CASE
WHEN operating_system='Default' THEN 1
ELSE 3
END AS osPoint,
CASE
WHEN browser='Default' THEN 1
ELSE 2
END AS browserPoint,
(devicePoint + osPoint + browserPoint) as 'Total'
FROM mytable
WHERE
(
(device = 'Desktop' AND operating_system='Ios' AND browser='Firefox')
OR
(device = 'Desktop' AND operating_system='Ios' AND browser='Default')
OR
(device = 'Desktop' AND operating_system='Default' AND browser='Firefox')
OR
(device = 'Desktop' AND operating_system='Default' AND browser='Default')
OR
(device = 'Default' AND operating_system='Ios' AND browser='Default')
OR
(device = 'Default' AND operating_system='Default' AND browser='Firefox')
OR
(device = 'Default' AND operating_system='Default' AND browser='Default')
)
答案 0 :(得分:1)
使用子查询:
SELECT
devicePoint,
osPoint,
browserPoint,
(devicePoint + osPoint + browserPoint) AS Total
FROM
(
SELECT *,
CASE WHEN device = 'Default' THEN 1 ELSE 5 END AS devicePoint,
CASE WHEN operating_system = 'Default' THEN 1 ELSE 3 END AS osPoint,
CASE WHEN browser = 'Default' THEN 1 ELSE 2 END AS browserPoint
FROM mytable
WHERE
(device = 'Desktop' AND operating_system='Ios' AND browser='Firefox') OR
(device = 'Desktop' AND operating_system='Ios' AND browser='Default') OR
(device = 'Desktop' AND operating_system='Default' AND browser='Firefox') OR
(device = 'Desktop' AND operating_system='Default' AND browser='Default') OR
(device = 'Default' AND operating_system='Ios' AND browser='Default') OR
(device = 'Default' AND operating_system='Default' AND browser='Firefox') OR
(device = 'Default' AND operating_system='Default' AND browser='Default')
) t;
不可能在定义它们的同一SELECT
中引用您的三个别名。但是,如果您使用上面的子查询方法,它们将可用。
答案 1 :(得分:1)
我提供了一个答案,因为您可以简化where
子句,因为MySQL支持元组。逻辑看起来像这样:
select t.*,
(devicePoint + osPoint + browserPoint) as 'Total'
from (select (case when device = 'Default' then 1 else 5 end) as devicePoint,
(case when operating_system = 'Default' then 1 else 3 end) as osPoint,
(case when browser = 'Default' then 1 else 2 end) as browserPoint
from mytable t
where (device, operating_system, browser) in
( ('Desktop', 'Ios', 'Firefox'),
('Desktop', 'Ios', 'Default'),
. . .
)
) t;
答案 2 :(得分:0)
这是最简单的 WHERE 子句。
SELECT *,
CASE
WHEN device='Default' THEN 1
ELSE 5
END AS devicePoint,
CASE
WHEN operating_system='Default' THEN 1
ELSE 3
END AS osPoint,
CASE
WHEN browser='Default' THEN 1
ELSE 2
END AS browserPoint,
(devicePoint + osPoint + browserPoint) as 'Total'
FROM mytable
WHERE
(device IN ('Desktop','Default') AND operating_system IN ('Ios','Default') AND browser IN ('Firefox','Default'))