TSQL-在SSMS的一行中显示两个查询的结果

问题描述 投票:0回答:2

我正在使用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 每个查询,这也将有所帮助)

tsql ssms resultset display recordset
2个回答
1
投票

这应该适用于任何数量的行,它假定您要按照显示的列中的值进行配对]

   With 
    TableA_CTE AS
    (
    SELECT TOP 1 colA as myCol1
    ,Row_Number() OVER (ORDER BY ColA)  AS RowOrder 
    FROM tableA
    ),
    TableB_CTE AS
    (
    SELECT TOP 1 colB as myCol2
    ,Row_Number() OVER (ORDER BY ColB)  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

1
投票

当前接受的答案有两个问题:I)行前缺少逗号:“表B为”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)
© www.soinside.com 2019 - 2024. All rights reserved.