我有一个选择查询
Select col1,col2,col3
from table;
该表包含以下行
col1 col2 col3
A | B | C
B | A | C
C | B | C
我需要通过比较多列来获得包含单个组合A,B,C的独特结果。
结果应该是像
这样的东西col1 col2 col3
A | B | C
可以更改结果行的顺序。
我怎样才能做到这一点?
答案 0 :(得分:2)
请试试这个,我不确定你的正确要求。但是上面给出的样本数据。我遇到过这个解决方案,
With CTE as
(
Select MIN(col1) as col1 from MyTable
)
Select * from CTE
cross apply
(
Select MIN(col2) as col2 from MyTable
where col2 <> CTE.col1
)as a
cross apply
(
Select MIN(col3) as col3 from MyTable
where col3 not in (CTE.col1,a.col2)
)as b
答案 1 :(得分:0)
SELECT *
FROM table
WHERE (col1 = 'A' AND col2 = 'B' AND col3 = 'C')
答案 2 :(得分:0)
如果列数和值已知,您也可以使用以下查询。
The CASE statement is the closest to IF in SQL
SELECT
CASE
WHEN (col1 = 'A' and col2 = 'B' and col3='C') or (col1 = 'C' and col2 = 'A' and col3='B') or (col1 = 'B' and col2 = 'C' and col3='A' )
THEN 1
ELSE 0
END as RESULT, *
FROM table
从结果中,您可以通过检查RESULT==1(integer)
如果您想要result as a boolean value
,请执行CAST
之类的
SELECT
CAST(
CASE
WHEN (col1 = 'A' and col2 = 'B' and col3='C') or (col1 = 'C' and col2 = 'A' and col3='B') or (col1 = 'B' and col2 = 'C' and col3='A' )
THEN 1
ELSE 0
END as RESULT_INT)
as RESUTL, *
FROM table