将表中列的旧日期和最新日期作为包含两行的单个列返回

时间:2017-05-19 02:55:44

标签: postgresql

我正在研究postgresql数据库服务器。我可以从单列中的列中获取最小和最大日期吗?我有两个表,我想得到存储在table1 cfrange列中的最小和最大日期,该列是字符变化的类型。 table1和table2使用sid映射。 表1:

    {
      "Query": {
        "inputs": {
          "headers": {
            "Content-Type": "application/json"
          },
          "method": "GET",
          "queries": {
            "f": "json",
            "temp": "\"test\": @json(body('http'))['candidates'][0]['location']['x']"
          },
          "uri": "https://testurl.com/restApi"
        },
        "runAfter": {

        },
        "type": "Http"
      }
    }

表2:

    "temp": "@json(body('http'))['candidates'][0]['location']['x']"

请参阅以下代码:

sid  cfrange  

100   3390
101   8000
102   5/11/2010
103   11/12/2016
104   01/03/2016
105   4000
106   4000
107   03/12/2017
108   03/11/2016
109   4/04/2018
110   10/12/2016

我希望输出如下:

sid  description

102  success
103  success
104  Proceeding
107  success
108  success

1 个答案:

答案 0 :(得分:0)

你可以将两个子查询联合在一起,一个查找最小值,另一个查找最大值:

WITH cte AS (
   SELECT
       t1.sid,
       t1.cfrange::date AS cfrange
   FROM table1 t1
   INNER JOIN table2 t2
       ON t1.sid = t2.sid
)
SELECT MIN(t.cfrange::date) AS min_max
FROM cte t
UNION ALL
SELECT MAX(t.cfrange::date)
FROM cte t
ORDER BY min_max

如果您想要一个可以直接从Java代码运行的查询,那么您可以直接嵌入CTE,例如

SELECT MIN(t.cfrange::date) AS min_max
FROM
(
   SELECT
       t1.sid,
       t1.cfrange::date AS cfrange
   FROM table1 t1
   INNER JOIN table2 t2
       ON t1.sid = t2.sid
) t
UNION ALL
SELECT MAX(t.cfrange::date)
FROM
(
   SELECT
       t1.sid,
       t1.cfrange::date AS cfrange
   FROM table1 t1
   INNER JOIN table2 t2
       ON t1.sid = t2.sid
) t
ORDER BY min_max