如果我有一个表格,如
1 A
1 B
1 A
1 B
2 C
2 C
我想从两列中选择不同的,以便我得到
1
2
A
B
C
我如何说出我的查询?是连接列并将它们包装在不同的函数运算符周围的唯一方法吗?
答案 0 :(得分:7)
您可以使用union
创建一个包含两列所有值的表格:
select col1 as BothColumns
from YourTable
union
select col2
from YourTable
与union all
不同,union
会删除重复项,即使它们来自union
的同一侧。
答案 1 :(得分:2)
请尝试:
Select Col1 from YourTable
union
Select Col2 from YourTable
UNION
删除重复记录(结果中的所有列都相同),UNION ALL
不会。
请检查What is the difference between UNION and UNION ALL
对于多列,您可以选择UNPIVOT。
SELECT distinct DistValues
FROM
(SELECT Col1, Col2, Col3
FROM YourTable) p
UNPIVOT
(DistValues FOR Dist IN
(Col1, Col2, Col3)
)AS unpvt;
答案 2 :(得分:2)
答案 3 :(得分:1)
试试这个 -
DECLARE @temp TABLE
(
Col1 INT
, Col2 NVARCHAR(50)
)
INSERT INTO @temp (Col1, Col2)
VALUES (1, 'ab5defg'), (2, 'ae4eii')
SELECT disword = (
SELECT DISTINCT dt.ch
FROM (
SELECT ch = SUBSTRING(t.mtxt, n.number + 1, 1)
FROM [master].dbo.spt_values n
CROSS JOIN (
SELECT mtxt = (
SELECT CAST(Col1 AS VARCHAR(10)) + Col2
FROM @temp
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'
)
) t
WHERE [type] = N'p'
AND number <= LEN(mtxt) - 1
) dt
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'
)
或试试这个 -
DECLARE @temp TABLE
(
a CHAR(1), b CHAR(1)
)
INSERT INTO @temp (a, b)
VALUES
('1', 'A'), ('1', 'B'), ('1', 'A'),
('1', 'B'), ('2', 'C'), ('2', 'C')
SELECT a
FROM @temp
UNION
SELECT b
FROM @temp
答案 4 :(得分:1)
因为您想要选择的内容位于不同的列中,您可以使用 union ,如下所示:
select distinct tarCol from
(select distinct column1 as tarCol from table
union
select distinct column2 from table) as tarTab
答案 5 :(得分:0)
您可以像这样使用来获取多个不同的列值
(SELECT DISTINCT `enodeb` as res,
"enodeb" as columnname
FROM `raw_metrics`)
UNION
(SELECT DISTINCT `interval` as res,
"interval" as columnname
FROM `raw_metrics`)