473,761 Members | 4,739 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL Syntax for distinct select

I'm trying to order a varchar column first numerically, and second
alphanumericall y using the following SQL:

SELECT distinct doc_number
FROM doc_line
WHERE product_id = 'WD' AND doc_type = 'O'
ORDER BY CASE WHEN IsNumeric(doc_n umber) = 1
THEN CONVERT(FLOAT, doc_number)
ELSE 999999999
END,
CASE WHEN IsNumeric(doc_n umber) = 1
THEN 'ZZZZZZZZZ'
ELSE doc_number
END;

When try executing this statement, I get the following error:

Server: Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is
specified.

If I take the "distinct" out, it works just fine, except for the fact that I
get many duplicates.

Does anyone have any suggestions?

Thanks,
Frank
Jul 20 '05 #1
3 10560
[posted and mailed, please reply in news]

blue (fl*****@config sc.com) writes:
I'm trying to order a varchar column first numerically, and second
alphanumericall y using the following SQL:

SELECT distinct doc_number
FROM doc_line
WHERE product_id = 'WD' AND doc_type = 'O'
ORDER BY CASE WHEN IsNumeric(doc_n umber) = 1
THEN CONVERT(FLOAT, doc_number)
ELSE 999999999
END,
CASE WHEN IsNumeric(doc_n umber) = 1
THEN 'ZZZZZZZZZ'
ELSE doc_number
END;

When try executing this statement, I get the following error:

Server: Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is
specified.


Try this:

SELECT doc_number
FROM (SELECT DISTINCT doc_number
FROM doc_line
WHERE product_id = 'WD'
AND doc_type = 'O') AS x
ORDER BY CASE WHEN doc_number NOT LIKE '%[0-9]%'
THEN CONVERT(FLOAT, doc_number)
ELSE 999999999
END,
CASE WHEN doc_number NOT LIKE '%[0-9]%'
THEN 'ZZZZZZZZZZ'
ELSE doc_number
END

I am using here a derived table, which logically is a temp table
created on the fly. However, the optimizer may pick a plan that
evades the table from actualy being created. This is a very
powerful SQL construct.

I also replaced your use of isnumeric, since this function is very
unreliable. It returns 1 if the string can be converted to some
numeric datatype, but you don't know which. For instance, a string
like '.' is numeric, but you cannot convert it to float. (But you
can convert it to money.) I assumed that you are only looking for
integer numbers. You don't have doc numbers like 1E234, have you?

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #2
Erland,

Thank you for your suggestion. However, I did get an error trying to run
your sql:

Server: Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.

When using the isNumeric, everything looks as expected:

SELECT doc_number
FROM (SELECT DISTINCT doc_number
FROM doc_line
WHERE product_id = 'WD'
AND doc_type = 'O') AS x
ORDER BY CASE WHEN IsNumeric(doc_n umber) = 1
THEN CONVERT(FLOAT, doc_number)
ELSE 999999999
END, CASE WHEN IsNumeric(doc_n umber) = 1 THEN 'ZZZZZZZZZ' ELSE doc_number
END

To answer your question about the doc numbers, which are customer order
numbers, yes, they can have any alphanumeric combination, with no special
characters.

Again, thanks for your help. Regards:

Frank

"Erland Sommarskog" <es****@sommars kog.se> wrote in message
news:Xn******** **************@ 127.0.0.1...
[posted and mailed, please reply in news]

blue (fl*****@config sc.com) writes:
I'm trying to order a varchar column first numerically, and second
alphanumericall y using the following SQL:

SELECT distinct doc_number
FROM doc_line
WHERE product_id = 'WD' AND doc_type = 'O'
ORDER BY CASE WHEN IsNumeric(doc_n umber) = 1
THEN CONVERT(FLOAT, doc_number)
ELSE 999999999
END,
CASE WHEN IsNumeric(doc_n umber) = 1
THEN 'ZZZZZZZZZ'
ELSE doc_number
END;

When try executing this statement, I get the following error:

Server: Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is
specified.


Try this:

SELECT doc_number
FROM (SELECT DISTINCT doc_number
FROM doc_line
WHERE product_id = 'WD'
AND doc_type = 'O') AS x
ORDER BY CASE WHEN doc_number NOT LIKE '%[0-9]%'
THEN CONVERT(FLOAT, doc_number)
ELSE 999999999
END,
CASE WHEN doc_number NOT LIKE '%[0-9]%'
THEN 'ZZZZZZZZZZ'
ELSE doc_number
END

I am using here a derived table, which logically is a temp table
created on the fly. However, the optimizer may pick a plan that
evades the table from actualy being created. This is a very
powerful SQL construct.

I also replaced your use of isnumeric, since this function is very
unreliable. It returns 1 if the string can be converted to some
numeric datatype, but you don't know which. For instance, a string
like '.' is numeric, but you cannot convert it to float. (But you
can convert it to money.) I assumed that you are only looking for
integer numbers. You don't have doc numbers like 1E234, have you?

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Jul 20 '05 #3
blue (fl*****@config sc.com) writes:
Thank you for your suggestion. However, I did get an error trying to run
your sql:

Server: Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.


Ah, that LIKE expression is complicated, and I got it wrong:
ORDER BY CASE WHEN doc_number NOT LIKE '%[0-9]%'


It should be:

ORDER BY CASE WHEN doc_number NOT LIKE '%[^0-9]%'

Exercise: try to understand how it works!

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
1867
by: middletree | last post by:
I've seen posts here and elsewhere which read something along the lines of "PULLNG MY HAIR OUT!!!!!" or "HELLLLPPP!". Well, I know that kind of subject line isn't descriptive, but I sure can relate right now. I've been struggling for days--days!!-- on this one simple query. I really need to get past this thing and move on. Please help. I have a classic ASP page, and it gives you 4 dropdowns. You can select any or none of them....
2
19263
by: Sri | last post by:
Hi, I am new to DB2 and I am using DB2 UDB 8.1 for Windows. I have a query which works fine in ORACLE and I am trying to find out equivalent query in DB2. SELECT sessi.ses sessions, sp1.speaker speaker1, sp2.speaker speaker2,
2
10536
by: Anne Heddal | last post by:
In the first line I'm trying to count the the unqiue values of the ID column, but I'm getting syntax error, any idea how to format the distinct count? SELECT Count(test.ID) AS IDCOUNT FROM (select distinct test.ID FROM test), Sum(test.balance) AS BAL, test.statement, billing.YYMM FROM billing INNER JOIN test ON billing.ID = test.ID WHERE (((test.invoice) Like "X*") AND ((test.due)=0) AND ((test.collections)=0)) GROUP BY test.statement,...
8
2223
by: Kevin Murphy | last post by:
Using PG 7.4.3 on Mac OS X 10.2.8, the following "insert into ... select ..." statement completed and then announced a syntax error, which seems bizarre. (Don't be confused by the fact that the two tables referred to (public.identifiers and original.identifiers) have slightly different column names.) egenome_dev=# \!cat /Users/murphy/cvs/egora/sql/data_port/port_identifiers.sql INSERT INTO public.identifiers (element_id, name, source,...
4
52445
MMcCarthy
by: MMcCarthy | last post by:
To view Access queries in SQL rather than Access query design - open the query design window and change the view to SQL: Select Statement SELECT FROM ; Append Statement INSERT INTO (, , ) VALUES ('value1', #value2#, value3); This assumes value1 is a string, value2 is a date and value 3 is some other datatype
7
2889
by: bryant | last post by:
Hi all. I am new to ASP and working in Expression Web. The following query displays the information I need in the gridview for a single record. SELECT "OE_HDR"."ORD_NO", "OE_HDR"."CUST_NAM", "OE_HDR"."SLS_MAN_NO", "OE_HDR"."SLS_MAN_INITIALS", "OE_HDR"."ORD_DAT", "OE_HDR"."SHIP_DAT" FROM "OE_HDR" WHERE ("OE_HDR"."ORD_NO"='174310') I also have DropDownList1 working properly. For the WHERE portion of
0
2558
by: dannyboy1990 | last post by:
I've been developing in vb.net for a few months now, well since i left school and one of my projects for my current company is to create a sql tool which is used on a daily basis to update, delete and select from the database. One of the functions i want this program to do is to highlight all sql words to make the program look alot 'cleaner'. I have achieved this to a point, I am currently at the stage where my code works, but not well or...
1
1252
by: NoviceDBLearner | last post by:
The SQL question I want to answer is: Get a list of the exhibitions and the number of artists in every exhibition. SELECT DISTINCT exhibitionname, COUNT(Artist) AS antal FROM Exhibition, ExhibitionOccasion, Painting WHERE Exhibition.ExhibtionID=ExhibtionOccasion.ExhibitionID And Painting.PaintID=ExhibitionOccasion.PaintID GROUP BY exhibitionname; Hello :)! I need to get rid of the doublets in this SQL code. What can I add here to the SQL...
5
1772
by: OldBirdman | last post by:
The SQL statement:SELECT tTitles.FKey FROM tTitles INNER JOIN tTitles ON (SELECT FROM tTitles WHERE (((Title) Like "*John*"))) = produces the error Because I can run the query SELECT DISTINCT FROM tTitles WHERE (((Title) Like "*John*")) by itself, I assume that this isn't really a syntax error. What's going on?
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9925
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3913
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.