Monday, February 13, 2012

"DISTINCT" problem...

I build an application that should show a on line magazin.
the articles in the magazin have name' article ID and "type"- "humor", "news" a ns so...
all of the article stored in a table and i use "SELECT DISTINCT type" to get the list of the types...
but' i want this types to be sorted, and if i use "ORDER BY theorder" i get an error massage- "you can't use DISTINCT with out including the column name".
so i changed to:
"SELECT DISTINCT type, theorder FROM..."
but then i get each type more then one' since the theorder column has diferent values...
how can i get the types, only one time each, and sort them?

Can you post your exact query? It should look something like this...
select distinct type from myTable order by theorder
Order by values do not have to appear in a select list, that only applies to the group by clause.

|||this is my query:cmd.CommandText = "SELECT DISTINCT type FROM tbl_paper WHERE alonNUM='" & alonNUM & "' ORDER BY theorder"and this the error massage and i copyed it from the screen:ORDER BY items must appear in the select list if SELECT DISTINCT is specified.|||This is a flaw with your data. You are saying you want to order by a field that is not distinct to each of your "types". How does the system know which one of the "theorder" fields to use for each of the "type" fields? I think you need to examine the data or how you want to display this field.
Anyhow, without getting multiple "types" back you cant do this type of query with the order by clause based on your data.

Nick|||This will happen even if your Data in the table is 100% correct. When? If you have 1:Many mapping, then you can't avoid having duplicate rows with join.
But in your case, it seems single table. So you table is not designed properly. If you add addition column to the select list then the combined value for all select columns will
be tried for distinctness. In this case {type, theorder} pair is distinct even though you might see multiple copies of the same type.|||Instead of DISTINCT, try a GROUP BY, and use a MAX() or a MIN() on the other column, like this:
SELECT
type,
MAX(theorder)
FROM
tbl_paper
WHERE
alonNUM='something'
GROUP BY
type
ORDER BY
2

This will give you one row per type, ordered by the maximum theorder value found for each type.

No comments:

Post a Comment