简体   繁体   中英

SQL greater than substring

I have a single SQL field like so:

          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?

Also, can this statement can be mutated to retrieve all rows with bathrooms greater than 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 :

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. Most DBMS support regular expressions, see eg 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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