我应该根据我的要求组合两个结果字段。例如,下面的查询提供了如图所示的结果。但我需要一个案例陈述,声明'wind'和'wind c'都是相同的,因此将其总和结合起来。
SELECT result, COUNT(*) AS total from(
SELECT t.Id AS Id,
CASE
WHEN LTRIM(RTRIM(AC)) = ' ' THEN AG
WHEN LOWER(AC) IS NOT NULL THEN LOWER(AC)
ELSE LOWER(AG)
END AS result,MaxDate,
FROM [DC_20160601] t
INNER JOIN ( SELECT Id, MAX(DateTime) AS MaxDate
FROM [DC_20160601]
GROUP BY Id) tm
ON t.Id = tm.Id AND t.DateTime = tm.MaxDate)
GROUP BY result
当前结果:
Result Total
Wind 1212
Wind c 345
sqrim 321
sqrim mob 123
预期结果:
Result Total
Wind mobile 1557
Sqrim mobile 444
答案 0 :(得分:0)
您可以通过substring_index
SELECT SUBSTRING_INDEX(`result`, ' ', 1);
现在按result
SELECT SUBSTRING_INDEX(`result`, ' ', 1), COUNT(*) AS total from(
SELECT t.Id AS Id,
CASE
WHEN LTRIM(RTRIM(AC)) = ' ' THEN AG
WHEN LOWER(AC) IS NOT NULL THEN LOWER(AC)
ELSE LOWER(AG)
END AS result,MaxDate,
FROM [DC_20160601] t
INNER JOIN ( SELECT Id, MAX(DateTime) AS MaxDate
FROM [DC_20160601]
GROUP BY Id) tm
ON t.Id = tm.Id AND t.DateTime = tm.MaxDate)
GROUP BY SUBSTRING_INDEX(`result`, ' ', 1)
答案 1 :(得分:0)
您可能会尝试在第一个空格之前提取所有内容并将其用于分组:
SUBSTRING_INDEX(result, ' ', 1)
否则,您需要维护一个查找表,以便将多个变体与单个结果匹配。
答案 2 :(得分:0)
您可以将case语句添加为外部查询。假设您的查询返回您发布的当前结果,以下是所需案例语句的示例:
select
case
when a.result = 'Wind' or a.result = 'Wind c' then 'Wind mobile'
else
case
when a.result = 'sqrim' or a.result = 'sqrim mob'
then 'Squirm mobile'
end
end as res,
sum(total)
from
(
SELECT result, COUNT(*) AS total from(
SELECT t.Id AS Id,
CASE
WHEN LTRIM(RTRIM(AC)) = ' ' THEN AG
WHEN LOWER(AC) IS NOT NULL THEN LOWER(AC)
ELSE LOWER(AG)
END AS result,MaxDate,
FROM [DC_20160601] t
INNER JOIN ( SELECT Id, MAX(DateTime) AS MaxDate
FROM [DC_20160601]
GROUP BY Id) tm
ON t.Id = tm.Id AND t.DateTime = tm.MaxDate)
GROUP BY result
) a
group by res
最好在查找表中指定case语句中的值并从那里获取它们,或者如果需要,你可以添加其他的作为case语句,但它不理想......
希望这有帮助!