简体   繁体   English

SQL大于子字符串

[英]SQL greater than substring

I have a single SQL field like so: 我有一个像这样的SQL字段:

          ROOMS
=======================
bedrooms 2, bathrooms 2
bedrooms 3, bathrooms 2
bedrooms 6, bathrooms 1
bedrooms 1, bathrooms 4
bedrooms 1, bathrooms 2
bedrooms 4, bathrooms 4
bedrooms 1, bathrooms 3

How can I form a single SELECT statement to retrieve all rows with bedrooms greater than 3? 如何形成单个SELECT语句来检索卧室大于3的所有行?

Also, can this statement can be mutated to retrieve all rows with bathrooms greater than 3? 此外,是否可以对此语句进行变异以检索浴室大于3的所有行?

EDIT 编辑

Yes, yes, yes, horrible data system. 是的,是的,是的,可怕的数据系统。 :) :)

Conceptually, however, is there a way to accomplish this? 但从概念上讲,有没有办法实现这一目标?

First, I hope I don't have to point out what a horrible, horrible data model this is. 首先,我希望我不必指出这是一个多么糟糕,可怕的数据模型。

With that out of the way: 除此之外:

You'll just have to parse the data in the field. 您只需要解析字段中的数据。 If the format is always like above, you might get away with using substr , as in : 如果格式总是如上所述,您可能会使用substr ,例如:

SELECT * FROM table WHERE SUBSTR(BEDROOMS, 9,1)>3

(no guarantee for the numbers :-) ). (不保证数字:-))。

If the format is more flexible (eg more than 9 bed-/bathrooms, bathrooms given first), you'll probably need to use a regular expression to parse. 如果格式更灵活(例如,超过9个床位/浴室,首先给出浴室),您可能需要使用正则表达式进行解析。 Most DBMS support regular expressions, see eg http://www.postgresql.org/docs/8.3/static/functions-matching.html 大多数DBMS支持正则表达式,参见http://www.postgresql.org/docs/8.3/static/functions-matching.html

Well, this is why normalization was 'invented' so that you won't end up with crappy schemas like this. 好吧,这就是为什么规范化是“发明的”,这样你就不会得到像这样糟糕的模式。 WHoever designed this should be ...., anyways. 无论如何设计这个应该是......,无论如何。

I suggest firstly to fix up the schema, and then this won't be a problem, but to answer your question, you can replace all occurences of the "bedrooms " with "" and then replace all ocurrences of the ", bathrooms " with say "-", then from there form a query. 我建议首先修复架构,然后这不会是一个问题,但要回答你的问题,你可以用“”替换所有“卧室”的出现,然后用“,”更换所有“浴室”说“ - ”,然后从那里形成一个查询。

SELECT CONVERT(int, SUBSTRING(ButcheredColumn, CHARINDEX('-', ButcheredColumn))) AS NumBedrooms
, CONVERT(int, RIGHT(ButcheredColumn, CHARINDEX('-', ButcheredColumn))) AS NumBathrooms
FROM (
    SELECT REPLACE(REPLACE(ROOMS, 'bedrooms ',''), ', bathrooms ', '-') AS ButcheredColumn
    FROM CrappyDesignedTable1
) AS ButhceredTable

might have to play with charindex a little to get the right column, then you can use this table as a subquery and select from it. 可能必须使用charindex一点来获得正确的列,然后您可以使用此表作为子查询并从中进行选择。 And I suggest if you dont know what a subquery is, to put all your tools down and go play angry birsds on your IPhone. 我建议如果你不知道子查询是什么,把你所有的工具放下来,然后在你的iPhone上玩愤怒的冒险。

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

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