Oracle PL / SQL查询顺序问题与Distinct有关

时间:2008-10-28 14:21:02

标签: sql oracle

有谁知道这个查询有什么问题?

 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;

我在职业生涯的大部分时间都做过T-Sql,这对我来说是正确的,但是这个查询是针对Oracle数据库而Toad只是将光标放在Order By部分的a.DateStored上。我确信这对于任何做PL / SQL的人都是基本的。

谢谢!

[编辑]为了将来参考,SQL * Plus给出的错误是:“ORA-01791:不是SELECTed表达式”

3 个答案:

答案 0 :(得分:15)

您需要修改查询:

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;

在执行DISTINCT时,您的订单需要是所选列之一。

答案 1 :(得分:2)

没关系,在SQL Plus中执行给了我一个更丰富的答案。 DateStored需要在select语句中,因此这有效:

    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;

答案 2 :(得分:2)

我认为order by子句的元素也必须在select子句中。