TSQL -- 在 SSMS 中的一行上显示两个查询的结果
TSQL -- display results of two queries on one row in SSMS
我正在使用 TSQL,SSMS v.17.9.1 底层数据库是 Microsoft SQL Server 2014 SP3
出于显示目的,我想连接两个查询的结果:
SELECT TOP 1 colA as 'myCol1' FROM tableA
--
SELECT TOP 1 colB as 'myCol2' FROM tableB
并在 SSMS 的一行中显示查询结果。
(TOP 1 指令有望保证每个查询的结果数量相同,这将有助于将它们一起显示。如果这可以推广到 TOP 10 per query 这也会有所帮助)
这应该适用于任意数量的行,它假设您要按显示的列中的值排序
With
TableA_CTE AS
(
SELECT TOP 1 colA as myCol1
,Row_Number() OVER (ORDER BY ColA DESC) AS RowOrder
FROM tableA
),
TableB_CTE AS
(
SELECT TOP 1 colB as myCol2
,Row_Number() OVER (ORDER BY ColB DESC) AS RowOrder
FROM tableB
)
SELECT A.myCol1, B.MyCol2
FROM TableA_CTE AS A
INNER JOIN TableB_CTE AS B
ON A.RowOrder = B.RowOrder
目前接受的答案有两个问题:
I) 行前缺少逗号:"Table B As"
II) TSQL 写的好像是递归的,所以我重新写成非递归的方式:
这是对实际在 T-SQL:
中有效的已接受答案的修改
USE [Database_1];
With
CTE_A AS
(
SELECT TOP 1 [Col1] as myCol1
,Row_Number() OVER (ORDER BY [Col2] desc) AS RowOrder
FROM [TableA]
)
,
CTE_B AS
(
SELECT TOP 1 [Col2] as myCol2
,Row_Number() OVER (ORDER BY [Col2] desc) AS RowOrder
FROM [TableB]
)
SELECT A.myCol1, B.myCol2
FROM CTE_A AS A
INNER JOIN CTE_B AS B
ON ( A.RowOrder = B.RowOrder)
我正在使用 TSQL,SSMS v.17.9.1 底层数据库是 Microsoft SQL Server 2014 SP3
出于显示目的,我想连接两个查询的结果:
SELECT TOP 1 colA as 'myCol1' FROM tableA
--
SELECT TOP 1 colB as 'myCol2' FROM tableB
并在 SSMS 的一行中显示查询结果。 (TOP 1 指令有望保证每个查询的结果数量相同,这将有助于将它们一起显示。如果这可以推广到 TOP 10 per query 这也会有所帮助)
这应该适用于任意数量的行,它假设您要按显示的列中的值排序
With
TableA_CTE AS
(
SELECT TOP 1 colA as myCol1
,Row_Number() OVER (ORDER BY ColA DESC) AS RowOrder
FROM tableA
),
TableB_CTE AS
(
SELECT TOP 1 colB as myCol2
,Row_Number() OVER (ORDER BY ColB DESC) AS RowOrder
FROM tableB
)
SELECT A.myCol1, B.MyCol2
FROM TableA_CTE AS A
INNER JOIN TableB_CTE AS B
ON A.RowOrder = B.RowOrder
目前接受的答案有两个问题: I) 行前缺少逗号:"Table B As" II) TSQL 写的好像是递归的,所以我重新写成非递归的方式:
这是对实际在 T-SQL:
中有效的已接受答案的修改USE [Database_1];
With
CTE_A AS
(
SELECT TOP 1 [Col1] as myCol1
,Row_Number() OVER (ORDER BY [Col2] desc) AS RowOrder
FROM [TableA]
)
,
CTE_B AS
(
SELECT TOP 1 [Col2] as myCol2
,Row_Number() OVER (ORDER BY [Col2] desc) AS RowOrder
FROM [TableB]
)
SELECT A.myCol1, B.myCol2
FROM CTE_A AS A
INNER JOIN CTE_B AS B
ON ( A.RowOrder = B.RowOrder)