开发者

SQL greater than substring

I have a single SQL fi开发者_JAVA百科eld 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 (e.g. 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 e.g. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜