我不知道该怎么做,但我似乎无法做到这一点。这是示例表:
+-----------+---------------+-------+--------------+
| CompanyID | CompanyName | Units | Municipality |
+-----------+---------------+-------+--------------+
| 123 | Coconuts Inc. | 1 | Kombu |
| 234 | Bubble Inc. | 10 | Dashi |
| 456 | NS Peel | 15 | Dashi NY |
| 789 | Ironbark | 23 | Dashi NY |
| 567 | Dr. Balanced | 12 | Oxford |
+-----------+---------------+-------+--------------+
我试图实现此输出:
+--------------+---------------+------------+
| Municipality | Company Count | Unit Count |
+--------------+---------------+------------+
| Kombu | 1 | 1 |
| Oxford | 1 | 12 |
| Dashi | 3 | 48 |
+--------------+---------------+------------+
是否可以在HAVING子句中使用LIKE函数?我试过了,结果并没有那么好。
答案 0 :(得分:2)
如果您只想保留在空间之前出现的市政名称部分,那么此查询将为您提供所需的结果,但请注意以这种方式处理此类问题(映射常用名称)不是很好的解决方案。拥有一个包含常用名称和变体之间映射的表会好得多。
编辑:我偶然使用了T-SQL语法,因为我没有注意到Postgresql标记...这里是一个使用正则表达式提取第一个单词的Postgresql查询 :
select
substring(municipality from E'\\w+\s?') as "Municipality",
count(distinct CompanyName) as "Company Count",
sum(units) as "Unit Count"
from table1
group by substring(municipality from E'\\w+\s?');
对于Postgresql
原始的T-SQL版本:
select
case
when charindex(' ', Municipality) = 0
then Municipality
else substring(Municipality, 0,charindex(' ', Municipality))
end as Municipality,
count(distinct [CompanyName]) as [Company Count],
sum(units) as [Unit Count]
from table1
group by
case
when charindex(' ', Municipality) = 0
then Municipality
else substring(Municipality, 0,charindex(' ', Municipality))
end
Sample SQL Fiddle(对于T-SQL)
映射表可能如下所示:
key alt_name
--- --------
Dashi Dashi NY
使用类似的表格,您可以使用左连接来匹配名称。
答案 1 :(得分:0)
如果你想分开Dashi和Dashi NY,那就像是:
SELECT municipality
, COUNT(1) as company_count
, SUM(units) as unit_count
FROM your_table
GROUP BY municipality
如果Dashi和Dashi NY属于一起,您可以使用另一个将Dashi和Dashi NY连接到特定ID的表,或者使用substr()
仅按前5或6个字符进行分组。
答案 2 :(得分:0)
这在一般情况下效果不好,但它对于一个adhoc查询就足够了,并且不需要任何麻烦的字符串解析函数:
select
case
when Municipality like 'Dashi%' then 'Dashi'
else Municipality
end, ...
...
group by
case
when Municipality like 'Dashi%' then 'Dashi'
else Municipality
end