Select to_number(size) as numSize, size as alphaSize from products order by numSizeand then just display the alphaSize...
SELECT [Size],
CONVERT(INTEGER,LTRIM(RTRIM(SUBSTRING([Size],1,CHARINDEX(' ',LTRIM(RTRIM([Size]))))))) AS numSize,
LTRIM(RTRIM(SUBSTRING([Size],CHARINDEX(' ',LTRIM(RTRIM([Size]))),LEN([Size])))) AS alphaSize
FROM Test
ORDER BY numSize,alphaSizeLEN([Size])LEN([Size])-CHARINDEX(' ',LTRIM(RTRIM([Size]))),LEN([Size]))+1orthogonality writes:Muddylemon has the choice, and doesn't understand why it's important.Thanks for making your condecension so clear.
For instance, your database is not normalized, which means that MOST aggregate functions won't work correctly in your database. Nor will updates. So when you decide you want to know how many bottles of V1agra you sold last month, the database won't be able to tell you -- if you're lucky. If you're unlucky, it'll tell you the wrong answer with no indication it's wrong.This is just stupid. "Size" is a customer facing descriptive field. You know what? My client likes to throw font tags into the product names - it annoys me, but I can live with it. Why? because we have things called primary keys. That little id field has a hell of a lot more to do with generating our reports than the descriptive fluff fields. We also have ingredients for these products. I suppose I could spend thousands of dollars of my clients money creating a system that would normalize all that data into discrete little chunks. Hell, then we could make a search app so our users could find all products with 300 milligrams of Acetyl L-Carnitine AND 100 mg of rice flour. But that's useless. The ingredients field is just descriptive information and sits happily in a little chunk of text.
Why should you believe me? I design databases for a living. What you're doing is pretty much the same as saying "I'm going to build a house, but I won't hire an architect or experienced craftsmen and I won't worry about conforming to city code." This will work basically until the first stiff breeze comes along.
For your immediate gratification, you need to:
1. use a function that finds the index of the first space character in the column;
2. make a substring from the first character to the space character index minus one;
3. convert that substring to a number;
4. make a substring of the remainder of the column;
5. sort on the substring in step four, then the substring in step 2.
Different SQL dialects have different names for the string functions and convert function you will need to use. as I do not know what dialect you are using, I can't write the actual SQL (and you should exercise your brain by doing it anyway, now that I've supplied the algorithm).
Note that once you've got the two substrings, you can also insert them in a better designed set of tables. I'd suggest a "quantity" column and a foreign key into a product table.
posted by orthogonality at 3:55 PM on February 16, 2006