【发布时间】:2021-07-15 06:03:40
【问题描述】:
假设一个有 3 列的表。每行代表每个值的唯一组合:
a a a
a a b
a b a
b b a
b b c
c c a
...
然而,我想要的是,
aab = baa = aba
cca = cac = acc
...
最后,我想以 CSV 格式获取这些值,作为每个值的组合,就像我附加的图像一样。
感谢您的帮助!
下面是生成我的问题的查询,请看一下!
--=======================================
--populate test data
--=======================================
drop table if exists #t0
;
with
cte_tally as
(
select row_number() over (order by (select 1)) as n
from sys.all_columns
)
select
char(n) as alpha
into #t0
from
cte_tally
where
(n > 64 and n < 91) or
(n > 96 and n < 123);
drop table if exists #t1
select distinct upper(alpha) alpha into #t1 from #t0
drop table if exists #t2
select
a.alpha c1
, b.alpha c2
, c.alpha c3
, row_number()over(order by (select 1)) row_num
into #t2
from #t1 a
join #t1 b on 1=1
join #t1 c on 1=1
drop table if exists #t3
select *
into #t3
from (
select *
from #t2
) p
unpivot
(cvalue for c in (c1,c2,c3)
) unpvt
select
row_num
, c
, cvalue
from #t3
order by 1,2
--=======================================
--these three rows should be treated equally
--=======================================
select *
from #t2
where concat(c1,c2,c3) in ('ABA','AAB', 'BAA')
--=======================================
--what i've tried...
--row count is actually correct, but the problem is that it ommits where there're any duplicate alphabet.
--=======================================
select
distinct
stuff((
select
distinct
'.' + cvalue
from #t3 a
where a.row_num = h.row_num
for xml path('')
),1,1,'') as comb
from #t3 h
【问题讨论】:
-
反透视、排序、透视、连接。向我们展示您不成功的查询尝试!
-
在我看来,按原样提取行并用编程语言进行组合会容易得多。
-
根据问题指南,请展示您的尝试并告诉我们您发现了什么(在本网站或其他地方)以及为什么它不能满足您的需求。
-
我找不到任何关于我的案例的帖子,似乎一切都是关于交叉连接以从多个列中找到不同的值,这并不是我想要的。
-
您关心输出 csv 中的元素顺序吗?例如,您可能会得到 37、30、30 或者您可能会得到 30、37、30 等,但是对于您的输出,您是否需要元素的标准排序,例如 37、30、30,或者任何顺序都可以接受?
标签: sql sql-server tsql unique combinations