2012-11-07 19 views
0

我对MySQL和MSSQL有更多的经验,但我不认为自己是SQL专家。有没有更有效的方法来统计Oracle SQL中聚合记录的数量?

我对Oracle数据库上运行的一些SQL工作有要求。甚至不确定版本,但它应该是最近(10,11 ??)。

无论如何,我必须计算跨越两个表的不同记录的数量。为了争辩,我们称之为masterdetail

下面的SQL为我提供了我想要的数据数量。但是,这个SQL最终将被放入一个UDF(或Oracle等价物)中。但我的问题是,有没有更好的方法?要么使用一些高级的Oracle优化,要么只是一个更好的SQL查询。

感谢

select count(*) from 
(
    select 
    mas.barcode 
    , det.barcode_val 

    from mas 
    inner join det on (det.trans_id = mas.trans_id and mas.trans_sub_id = det.trans_sub_id) 
    where 
    mas.trans_id = 12345 
    and det.code_type = 'COMMODORE' 
    group by 
    mas.barcode 
    , det.barcode_val 
); 

数据:

MAS 

trans_id  trans_sub_id  barcode 
------------------------------------- 
12345     1  COM_A 
12345     2  COM_A 
12345     3  COM_B 


DET 

trans_id  trans_sub_id  code_type  barcode_val 
------------------------------------------------------- 
12345     1  COMMODORE  C64 
12345     1  COMMODORE  C64 
12345     1  TANDY   TRASH80 
12345     2  COMMODORE  C128 
12345     2  ATARI   800XL 
12345     2  COMMODORE  AMIGA500 
12345     3  COMMODORE  C64 


Results before count 
-------------------- 
COM_A  C64 
COM_A  C128 
COM_A  AMIGA500 
COM_B  C64 


Results after count 
------------------- 
4 

回答

1
SELECT 
COUNT(DISTINCT mas.barcode || det.barcode_val) 
FROM mas 
INNER JOIN det 
ON (det.trans_id = mas.trans_id and mas.trans_sub_id = det.trans_sub_id) 
WHERE 
mas.trans_id = 12345 
AND det.code_type = 'COMMODORE' 

SELECT COUNT(*) FROM ( 
    SELECT DISTINCT mas.barcode, det.barcode_val 
    FROM mas 
    INNER JOIN det 
    ON (det.trans_id = mas.trans_id and mas.trans_sub_id = det.trans_sub_id) 
    WHERE 
    mas.trans_id = 12345 
    AND det.code_type = 'COMMODORE' 
) 
+0

我不得不使用'||'而不是逗号。有什么我失踪,因为除此之外,你的答案没有奏效。我得到了'无效的参数数量'。谢谢 – cbmeeks

+0

抱歉,更正。 – Emyl

0

如果使用

COUNT(DISTINCT mas.barcode || det.barcode_val) 

确保把管道之间的分隔符:

COUNT(DISTINCT mas.barcode || '-' || det.barcode_val) 

例如想象以下场景:

Column1 Column2 Column1 || Column2 Column1 || '-' || Column2 
    A   B   AB     A-B 
    AB  <null>  AB     AB- 
    1   201  1201     1-201 
    <null>  1201  1201     -1201 

这个表有4行有4个不同的值。但是,如果你尝试一个

COUNT(DISTINCT COLUMN1 || COLUMN2) 

你会得到只有2“不同”的组。 只是试图避免这些角落案件的提示。

相关问题