我将有一个名为VISIT表的SQL表。
我有3列
工作站,类别,按钮
1,1,1
1,2,3
1,1,2
2,1,1
2,3,1
2,1,2
如何查询该表以获取一个查询语句中每列的不同值?
结果应该是...... ..
工作站,类别,按钮
1,1,1
2,2,2
- ,3,3
我可以用3个不同的查询来做到这一点。我只是想知道这可以在一个查询中完成,因为这将使程序运行得更快。
答案 0 :(得分:2)
尝试使用每列列进行此操作是IMO的一个错误;只需在两列中执行,然后在调用者处选择列:
SELECT DISTINCT 'WS' AS [Col], WORKSTATION AS [Value] FROM VISIT
UNION ALL
SELECT DISTINCT 'CA' AS [Col], CATEGORY AS [Value] FROM VISIT
UNION ALL
SELECT DISTINCT 'BU' AS [Col], BUTTON AS [Value] FROM VISIT
与:
或多或少相同SELECT 'WS' AS [Col], WORKSTATION AS [Value] FROM VISIT
UNION
SELECT 'CA' AS [Col], CATEGORY AS [Value] FROM VISIT
UNION
SELECT 'BU' AS [Col], BUTTON AS [Value] FROM VISIT
这是一次往返等等。我可能会对第一列使用整数(甚至可能是tinyint
)(客户端应该知道1映射到WORKSTATION等)而不是varchar,但上面只给出了味道。
编辑评论;以下考虑到:
TSQL:
DECLARE @VISIT TABLE (WORKSTATION int, CATEGORY varchar(10), BUTTON int)
INSERT @VISIT VALUES (1,'1',1)
INSERT @VISIT VALUES (1,'2',3)
INSERT @VISIT VALUES (2,'1',2)
INSERT @VISIT VALUES (10,'1',1)
INSERT @VISIT VALUES (10,'3',1)
INSERT @VISIT VALUES (10,'1',2)
SELECT x.Col, x.Value
FROM (
SELECT CAST(1 as tinyint) AS [Col], ROW_NUMBER() over(order by WORKSTATION)
AS [Sort], CONVERT(varchar(20), WORKSTATION) AS [Value] FROM @VISIT
UNION
SELECT CAST(2 as tinyint) AS [Col], ROW_NUMBER() over(order by CATEGORY)
AS [Sort], CATEGORY AS [Value] FROM @VISIT
UNION
SELECT CAST(3 as tinyint) AS [Col], ROW_NUMBER() over (order by BUTTON)
AS [Sort], CONVERT(varchar(20), BUTTON) AS [Value] FROM @VISIT
) x ORDER BY x.Col, x.Sort
答案 1 :(得分:0)
一些想法......
两个完整的外部联接:
SELECT DISTINCT w.workstation, c.category, b.button
FROM VISIT w FULL OUTER JOIN VISIT c ON (w.workstation = c.category)
FULL OUTER JOIN VISIT b ON (w.workstation = b.button OR c.category = b.button)
VISIT的子查询也可能加快速度:
SELECT w.workstation, c.category, b.button
FROM (SELECT DISTINCT workstation FROM VISIT) w
FULL OUTER JOIN (SELECT DISTINCT category FROM VISIT) c
ON (w.workstation = c.category)
FULL OUTER JOIN (SELECT DISTINCT button FROM VISIT) b
ON (w.workstation = b.button OR c.category = b.button)
如果您愿意,可以订购:
ORDER BY COALESCE(w.workstation, c.category, b.button)