2015-12-31 23 views
0
  • Nb。我正在使用PostgreSQL。
  • Nb1。为了简单起见,我只显示了这篇文章的两个相关列,原始表格有更多行&列。

我有一个表叫 '内容' 是这样的:从'字母数字+符号'字符串中提取的范围值组中的数据[PostgreSQL]

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<table border="1" style="width:100%"> 
 
    <tr> 
 
    <td>id</td> 
 
    <td>data</td> \t \t 
 
    </tr> 
 
    <tr> 
 
    <td>4009</td> 
 
    <td>"duration"=>"101", "preview_version"=>"", "twitter_profile"=>"", "creator_category"=>"association", "facebook_profile"=>"", "linkedin_profile"=>"", "personal_website"=>"", "content_expertise_type"=>"image", "content_expertise_categories"=>"1,2,3"</td> \t \t 
 
    </tr> 
 
    <tr> 
 
    <td>4865</td> 
 
    <td>"duration"=>"108", "preview_version"=>"", "twitter_profile"=>"", "creator_category"=>"association", "facebook_profile"=>"", "linkedin_profile"=>"", "personal_website"=>"", "content_expertise_type"=>"image", "content_expertise_categories"=>"4,6"</td> \t \t 
 
    </tr> 
 
</table> 
 

 
</body> 
 
</html>

从这个表中我需要使用此查询,提取时间值:

select id,data->'duration' as data from contents 

它给了我下面的结果(再次,原始表将返回更多的条目和在“数据”列中的某些值将重合的原因,我需要他们组范围):

+------+------+ 
| id | data | 
+------+------+ 
| 4009 | 101 | 
| 4865 | 108 | 
+------+------+ 

现在我有“数据”值我想在不同的范围来标记他们

SELECT d.id, 
    case when d.data >= 0 and d.data< 10 then '0-9' 
    when d.data >= 10 and d.data< 20 then '10-19' 
    else '20-500' end as range 
FROM (SELECT id,data->'duration' as data FROM contents) as d 

但这里的查询返回此错误:

ERROR: operator does not exist: text >= integer LINE 3: case when d.data >= 0 and d.data< 10 then '0-9' ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.

此我希望能组范围这样的后

任何帮助实现这个分组任务将非常感谢!

期待得到答案! :-)

谢谢!

回答

0

,如果你投的价值它应该工作:

SELECT d.id, 
     (case when d.data >= 0 and d.data< 10 then '0-9' 
      when d.data >= 10 and d.data< 20 then '10-19' 
      else '20-500' 
     end) as range 
FROM (SELECT id, (data->'duration')::int as data FROM contents 
    ) d 
+0

噢,快速和容易。你是伟人!谢谢@戈登! – Henry

1

Postgres里的JSON值始终为字符串,就必须投。对于从JSON取整数值域中有一个特殊的运算符->>

尝试获取持续时间整型值像

select id, data->>'duration' as data from contents 

更多信息http://www.postgresql.org/docs/9.3/static/functions-json.html

+0

嗨@sema,感谢您的关注。如果我使用它,我得到这个错误:错误:操作符不存在:hstore - >>未知 行7:从(选择id,数据 - >>'持续时间'作为数据从内容 ^ 提示:没有操作符匹配你可能需要添加明确的类型转换 – Henry

+0

啊,我假设你使用'json'类型而不是'hstore' :)我的回答是关于json,hstore的情况在下面回答:) – Semjon

+0

好吧,没问题!乐意回顾所有提议的解决方案!谢谢大家! – Henry