如何正确选择子查询
How to selecting subqueries correctly
我有两个查询返回一个条目。我怎样才能 select 这两个 table?
查询 1:Select max([column3]) from [table1] => 42
查询 2:Select Top 1 [column1] from [table1] => 'test'
我想要这样的结果集
result1
result2
42
'test'
但是如何正确地做呢?我可以不知何故 select 吗?
您可以使用 ROW_NUMBER
,两次:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY column3 DESC) rn1,
ROW_NUMBER() OVER (ORDER BY some_col) rn2
FROM table1
)
SELECT MAX(CASE WHEN rn1 = 1 THEN column3 END) AS result1,
MAX(CASE WHEN rn2 = 1 THEN column1 END) AS result2
FROM cte;
请注意,我假设存在一列 some_col
,您打算将其用于选择 column1
值。
我有两个查询返回一个条目。我怎样才能 select 这两个 table?
查询 1:Select max([column3]) from [table1] => 42
查询 2:Select Top 1 [column1] from [table1] => 'test'
我想要这样的结果集
result1 | result2 |
---|---|
42 | 'test' |
但是如何正确地做呢?我可以不知何故 select 吗?
您可以使用 ROW_NUMBER
,两次:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY column3 DESC) rn1,
ROW_NUMBER() OVER (ORDER BY some_col) rn2
FROM table1
)
SELECT MAX(CASE WHEN rn1 = 1 THEN column3 END) AS result1,
MAX(CASE WHEN rn2 = 1 THEN column1 END) AS result2
FROM cte;
请注意,我假设存在一列 some_col
,您打算将其用于选择 column1
值。