按拆分数据分组的sql

q8l4jmvw  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(357)

我有一张这样的table:

Name  |      Temperament
----------------------------------------
 "Husky" | "Smart, Loyal, Cute"
 "Poodle"| "Smart, Cute"
 "Golden"| "Cute, Loyal, Caring, Loving"

我想把这些数据作为一组气质的数据。例如:

Temperament |             Name            | Count(Optional)
-----------------------------------------------------------   
"Smart"     | "Poodle", "Husky"           | 2
"Loyal"     | "Husky", "Golden"           | 2
"Cute"      | "Poodle", "Golden", "Husky" | 3
"Caring"    | "Golden"                    | 1
"Loving"    | "Golden"                    | 1

我的问题是,我找不到一种方法来拆分表中的字符串并操作这些数据。如果有人能帮我解决这个问题就太好了。
如果纯sql做不到,告诉我使用的是实体框架可能会有帮助,如果可以用它来编写解决方案,可能会更好。
谢谢大家。

ffscu2ro

ffscu2ro1#

这可以在纯sql中完成。在oracle中,可以使用regexp函数和正则表达式拆分分隔字符串,然后使用字符串聚合生成每个字符串的名称列表:

with cte (name, temperament, temp, cnt, lvl) as (
    select 
        name, 
        temperament, 
        regexp_substr (temperament, '[^, ]+', 1, 1) temp, 
        regexp_count(temperament, ',') cnt,
        1 lvl 
    from mytable
    union all
    select 
        name, 
        temperament, 
        regexp_substr (temperament, '[^, ]+', 1, lvl  + 1), 
        cnt,
        lvl + 1
    from cte
    where lvl <= cnt
)
select 
    temp temperament, 
    listagg(name, ', ') within group(order by name) name, 
    count(*) cnt
from cte
group by temp
order by 1

db小提琴演示:

TEMPERAMENT | NAME                  | CNT
:---------- | :-------------------- | --:
Caring      | Golden                |   1
Cute        | Golden, Husky, Poodle |   3
Loving      | Golden                |   1
Loyal       | Golden, Husky         |   2
Smart       | Husky, Poodle         |   2
ocebsuys

ocebsuys2#

如果有人需要答案:
var result=(from t in((from t1 in db.mytables select new{tmp=t1.temp1}).concat(from t2 in db.mytables select new{tmp=t2.temp2}).concat(from t3 in db.mytables select new{tmp=t3.temp3}))将t.tmp按t.tmp分组到g select new{tmp=g.key,cnx=g.count()}).tolist();
希望它能帮助别人!

相关问题