如何在Oracle 10g的GROUP BY子句中获取其他不在列中的列?

时间:2019-04-09 13:16:43

标签: sql oracle group-by oracle10g

我正在键入SELECT语句以检索每个客户在销售收据历史记录中首次出现的信息,我有以下语句可检索有关client_id和sales_receipt日期的信息,但我需要每个收据的sales_receipt_id。你能帮助我吗?谢谢!

我正在使用Toad for Oracle 9.7.2.5中连接的Oracle Database 10G。

SELECT cli_codigo AS client_id, MIN(cmp_fecha_contable) AS sales_receipt_date
FROM   comprobantes
WHERE  cli_codigo IS NOT NULL
GROUP BY cli_codigo
ORDER BY cli_codigo ASC;

此语句实际上使我们运行良好,但我也需要receive_id。 (所有列都在名为“ comprobantes”的同一表中。

我希望输出:

RECEIPT_ID  CLIENT_ID   RECEIPT_DATE    
201203000174    061     3/19/2012    
201203000027    118     3/19/2012    
201203000028    166     3/19/2012    
201203000029    139     3/19/2012    
201203000031    055     3/19/2012

3 个答案:

答案 0 :(得分:1)

您可以使用keep

SELECT cli_codigo AS client_id,
       MIN(cmp_fecha_contable) AS sales_receipt_date,
       MIN(receipt_id) KEEP (DENSE_RANK FIRST ORDER BY cmp_fecha_contable) as first_receipt_id
FROM comprobantes
WHERE cli_codigo IS NOT NULL
GROUP BY cli_codigo
ORDER BY cli_codigo ASC;

这本质上是一个聚合first_value()函数。尽管语法有点笨拙,但是keep是聚合查询中非常强大的结构。

答案 1 :(得分:0)

select comprobantes.* 
from comprobantes 
left join 
(
SELECT cli_codigo AS client_id, MIN(cmp_fecha_contable) AS sales_receipt_date
FROM   comprobantes
WHERE  cli_codigo IS NOT NULL
GROUP BY cli_codigo
ORDER BY cli_codigo ASC
) a on a.client_id = comprobantes.cli_codigo and comprobantes.cmp_fecha_contable = a.sales_receipt_date

答案 2 :(得分:0)

列必须在分组依据或聚合函数中。 因此,您可以这样做:

SELECT cli_codigo AS client_id, MIN(cmp_fecha_contable) AS sales_receipt_date, min(RECEIPT_ID) 
FROM   comprobantes
WHERE  cli_codigo IS NOT NULL
GROUP BY cli_codigo
ORDER BY cli_codigo ASC

SELECT cli_codigo AS client_id, MIN(cmp_fecha_contable) AS sales_receipt_date, RECEIPT_ID
FROM   comprobantes
WHERE  cli_codigo IS NOT NULL
GROUP BY cli_codigo, RECEIPT_ID
ORDER BY cli_codigo ASC;