简体   繁体   English

从嵌套的 json sql 查询计算 Datediff

[英]Calculating Datediff from nested json sql query

I am trying to use datediff() to find the age of a person in a postgres db (from their date of birth(. I know I can run datediff() like this我正在尝试使用datediff()在 postgres 数据库中查找一个人的年龄(从他们的出生日期(。我知道我可以像这样运行datediff()

SELECT DATEDIFF(current_date, '2021-01-24');

The query i use to get date of birth is (its in json)我用来获取出生日期的查询是(它在 json 中)

select date_of_birth from (select attrs::json->'info'->>'date_of_birth' from users) as date_of_birth;

This gives me output like这给了我 output 之类的

date_of_birth      
--------------
 (2000-11-03)
 (2000-06-11)
 (2000-05-31)
 (2008-11-26)
 (2007-11-09)
 (2020-03-26)
 (2018-06-30)

I tried using我尝试使用

SELECT DATEDIFF(current_date, (select date_of_birth from (select attrs::json->'info'->>'date_of_birth' as date_of_birth from users));

It doesn't work.它不起作用。 I tried several permutations but i can't get it to work.我尝试了几种排列,但我无法让它工作。 How should I edit my query to calculate the user age?我应该如何编辑我的查询来计算用户年龄?

This query:这个查询:

select date_of_birth 
from (
  select attrs::json->'info'->>'date_of_birth' 
from users
) as date_of_birth;

Returns the row rather than a column, (the column expression for the extracted date value has no defined alias).返回而不是列(提取的日期值的列表达式没有定义的别名)。 It's like using select users from users .这就像select users from users一样。 You need to make `date_of_birth_ a column alias (not a table alias) and use that in the outer query.您需要将 `date_of_birth_ 设为列别名(不是表别名)并在外部查询中使用它。

To get the difference between two dates,just subtract them but you need to cast the valued to a date to be able to do that.要获得两个日期之间的差异,只需将它们相减,但您需要将值转换为date才能做到这一点。

select current_date - u.date_of_birth 
from (
  select (attrs::json->'info'->>'date_of_birth')::date as date_of_birth
  from users
) as u;

Or without a derived table:或者没有派生表:

select current_date - (u.attrs::json->'info'->>'date_of_birth')::date
from users as u

Apparently your dates are stored in a non-standard format.显然,您的日期以非标准格式存储。 In that case you can't use as cast, but you need to use the to_date() function:在这种情况下,您不能用作演员,但您需要使用to_date() function:

to_date(u.attrs::json->'info'->>'date_of_birth', 'mm:dd:yyyy')

If you are storing JSON in the attrs column you should convert it from a text (or varchar column to a proper json (or better jsonb ) so you don't need to cast it all the time.如果您将 JSON 存储在attrs列中,您应该将其从text (或varchar列转换为正确的json (或更好的jsonb ),这样您就不需要一直转换它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM