小编典典

从多值列查询唯一值

sql

我正在尝试查询“标签”列中的所有唯一值。标签列中的每一行都可以包含多个值。因此,在不被迫进行规范化的情况下,如何查询多值列?

示例行:

Networking
Professionalism
Time Management
Communication, Networking
Career Management, Professionalism
Networking
Communication
Attitude, Interpersonal Skills, Professionalism
Business Protocol, Career Management, Communication, Leadership
Business Protocol, Networking

阅读 179

收藏
2021-04-07

共1个答案

小编典典

如果最大元素数量是可预测的,则可以使用此方法(请注意,您需要使用UNION,而不是UNION ALL

Select DISTINCT thefield from thetable where Instr(thefield, ',') = 0
UNION 
Select Distinct Mid(thefield, 1, Instr(thefield, ',')) from thetable Where len(thefield) - len(replace(thefield,',','')) = 1
UNION 
Select Distinct Mid(thefield, Instr(thefield, ',')+1) from thetable Where len(thefield) - len(replace(thefield,',','')) = 1
UNION 
Select Distinct Mid(thefield, Instr(thefield, ',')+1, Instr(Instr(thefield, ',')+1,thefield, ',')) from thetable Where len(thefield) - len(replace(thefield,',','')) = 2
UNION 
Select Distinct Mid(thefield, Instr(Instr(thefield, ',')+1,thefield, ',')+1) from thetable Where len(thefield) - len(replace(thefield,',','')) = 2
--.. and so on (repeat last two Selects as many time as you wish, increasing the where condition by one for each pair)

看起来有些笨拙,但应该可以完成工作。未经测试,因此,在值之前或之后可能会出现一个逗号逗号

2021-04-07