我运行了以下查询以获取表中的第一行和最后一行。
SELECT Start, End, Start1, End1
FROM
(SELECT Start AS Start, End AS End
FROM [TB1] WHERE Id = 251 ORDER BY DateTime DESC LIMIT 1),
(SELECT Start1 AS Start1, End1 AS End1
FROM [TB2] WHERE Id = 251 ORDER BY DateTime LIMIT 1);
我得到如下输出:
Start End Start1 End1
25.32 -98.55 null null
null null 29.81 -98.32
我试图以下面的格式获得输出:
Start End Start1 End1
25.32 -98.55 29.81 -98.32
答案 0 :(得分:1)
使用max
,结果将在一行。
SELECT max(Start) start, max(End) end, max(Start1) start1, max(End1) end1
FROM
(SELECT Start AS Start, End AS End
FROM [TB1] WHERE Id = 251 ORDER BY DateTime DESC LIMIT 1),
(SELECT Start1 AS Start1, End1 AS End1
FROM [TB2] WHERE Id = 251 ORDER BY DateTime LIMIT 1);
答案 1 :(得分:1)
我觉得你的问题是“部分的”,接下来将是如何为所有Id做同样的事情!见下文
SELECT Id, Start, End, Start1, End1
FROM
(SELECT Id, Start, End
FROM (
SELECT
Id, Start AS Start, End AS END,
ROW_NUMBER() OVER(PARTITION BY Id ORDER BY DateTime DESC) AS win
FROM [TB1])
WHERE win = 1
) AS t1
JOIN
(SELECT Id, Start1, End1
FROM (
SELECT
Id, Start1 AS Start1, End1 AS End1,
ROW_NUMBER() OVER(PARTITION BY Id ORDER BY DateTime) AS win
FROM [TB2])
WHERE win = 1
) AS t2
ON t1.Id = t2.Id
答案 2 :(得分:1)
如果您希望单个表(而非两个)上的第一行和最后一行,则可以使用ARRAY_AGG
ORDER BY
和LIMIT
standard SQL中的WITH T AS (
SELECT 251 AS Id, 10.0 AS Start, -15 AS `End`, DATE('2016-11-09') AS DateTime UNION ALL
SELECT 251, 25.32 AS Start, -98.55, DATE('2016-11-10') UNION ALL
SELECT 251, 29.81, -98.32, DATE('2016-01-01')
)
SELECT
ARRAY_AGG(STRUCT(Start, `End`)
ORDER BY DateTime DESC LIMIT 1)[OFFSET(0)] AS first_row,
ARRAY_AGG(STRUCT(Start AS Start1, `End` AS End1)
ORDER BY DateTime ASC LIMIT 1)[OFFSET(0)] AS last_row
FROM T
WHERE Id = 251;
来计算它(取消选中"使用旧版SQL"在"显示选项"在用户界面中)。
<body bgcolor="$color_name">;
一般来说,这可能比使用分析函数快一点,但我还没有做过任何具体的比较。