我正在尝试从包含地址(包括街道,邮政编码等)的列中计算出独特的国家/地区。它们之间以分号分隔,与该国家/地区排在第二位,例如:
public class ExecutionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var result = 0;//code to see if they have permission returns either 0 or 1
if (result == 0)
{
actionContext.Response = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.Unauthorized,
Content = new StringContent("Unauthorized User")
};
}
base.OnActionExecuting(actionContext);
}
}
我尝试将列分开,并删除不需要的部分,然后计算唯一的国家/地区,但是我无法再次将查询合并为一个。一个查询对此会是什么样子?
答案 0 :(得分:4)
您可以使用SUBSTRING_INDEX
提取字符串的国家/地区部分,然后提取COUNT DISTINCT
的值:
SELECT COUNT(DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(data, ';', 2), ';', -1))
FROM test
答案 1 :(得分:0)
此查询将为您提供唯一国家/地区的数量:
SELECT
COUNT(DISTINCT REGEXP_SUBSTR (description, '[^;]+', 1, 2)) as unique_country_count
FROM address;
注意:此查询假设您的表名称称为地址,而该列称为描述。
样本数据:
description
----------------------------------------
FirstName LastName; USA; Restofaddress
FirstName LastName; USA; Restofaddress
FirstName LastName; China; Restofaddress
独特的国家是美国和中国,因此计数为2。
结果:
unique_country_count
--------------------
2