2

So this query is for a combo box of a database, and I've tried to order the list of items that appears inside, however it wont work. This is the query

Select "*",  "<<All Records>>" 
FROM Treatment 
UNION 
Select Treatment.TreatmentID, Treatment.Treatment 
From Treatment;

I tried adding Order By's for both parts of the query, and tried switching it around, still not working, any ideas? I tried to ORDER BY Treatment.TreatmentID, since that's the primary key for that table

The ORDER BY works on the second part itself, when there was no union involved, by the way. Currently, the data is sorting as this :

<<All Records>>
1 Treatment Name
8 Treatment Name
9 Treatment Namw
10 Treatment Name
11 Treatment Name 
12 Treatment Name
2 Treatment Name
Etc...

The number is the ID, and the Treatment name (Obviously not all called Treatment Name) are from the field Treatment name. I need "All Records" up top, and then sort the data from the second part of the union, by the ID.

Thanks in advance,

Adam

amartin94
  • 505
  • 3
  • 19
  • 35

3 Answers3

6

One thing that you can is add a field that you can use to sort the data:

Select "*" as AllRec,  "<<All Records>>" as Allrecords, 1 as SortOrder
FROM Treatment 
UNION 
Select Treatment.TreatmentID, Treatment.Treatment, 2 as SortOrder
From Treatment
ORDER BY SortOrder, AllRec;

The ORDER BY is always applied last so it will not know the Treatment.TreatmentID column name.

Taryn
  • 242,637
  • 56
  • 362
  • 405
1

You can do this:

Select q.* from 
(Select "*", "<>" 
FROM Treatment UNION 
Select Treatment.TreatmentID, Treatment.Treatment 
From Treatment) q
ORDER BY q.whatever
DNadel
  • 495
  • 1
  • 5
  • 13
0

SELECT, "--- All Records ---", SortOrder = 0

UNION

SELECT TreatmentID, Treatment, SortOrder = 1 FROM Treatment

ORDER BY SortOrder, Treatment;


(Only 2 and half years late!)

AJA
  • 1
  • Opps - first select should be :SELECT 0 AS TreatmentId, "--- All Record ---" AS Treatment, SortOrder = 0 – AJA Jun 02 '15 at 22:28