tags:

views:

1159

answers:

3

Does anyone know what is wrong with this query?

 SELECT DISTINCT c.CN as ClaimNumber, 
         a.ItemDate as BillReceivedDate, c.DTN as
 DocTrackNumber
         FROM ItemData a,
         ItemDataPage b,
         KeyGroupData c
         WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
         AND a.ItemNum = b.ItemNum
         AND b.ItemNum = c.ItemNum
         ORDER BY a.DateStored DESC;

I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL.

Thanks!

[EDIT] For future reference, the error given by SQL*Plus was: "ORA-01791: not a SELECTed expression"

+2  A: 

Nevermind, executing in SQL Plus gave me a more informative answer. The DateStored needs to be in the select statement so this works:

    SELECT DISTINCT c.CN as ClaimNumber,          
a.ItemDate as BillReceivedDate, 
c.DTN as DocTrackNumber, 
a.DateStored         
FROM ItemData a,         
ItemDataPage b,         
KeyGroupData c         
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)         
AND a.ItemNum = b.ItemNum         
AND b.ItemNum = c.ItemNum         
ORDER BY a.DateStored DESC;
Chris Conway
Just the conclusion that I came to...
Carl
If you are leaving this question here for future reference then we should probably note that the error given is: ORA-01791: not a SELECTed expression
Carl
+12  A: 

You will need to modify the query as such:

SELECT DISTINCT c.CN as ClaimNumber, 
         a.ItemDate as BillReceivedDate, c.DTN as
 DocTrackNumber, a.DateStored
         FROM ItemData a,
         ItemDataPage b,
         KeyGroupData c
         WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
         AND a.ItemNum = b.ItemNum
         AND b.ItemNum = c.ItemNum
         ORDER BY a.DateStored DESC;

When doing a DISTINCT your order by needs to be one of the selected columns.

Brian Schmitt
+1  A: 

I believe that the elements of the order by clause must also be in the select clause.

Just to clarify: This is true because of the DISTINCT. In many queries it is possible to order by a column that is not in the select list, e.g. SELECT name FROM emp ORDER BY empid.
Dave Costa