如何获取列数

时间:2018-09-12 18:59:31

标签: oracle count sql-order-by

我对oracle还是很陌生,并试图弄清楚如何获取查询返回的每个供应商的端口数。

select distinct
  count(pi.port), pi.RACK, pi.SHELF, pi.SLOT, pi.PORT, pi.BROADBAND_CIRCUIT_ID, d.DSLAM, d.VENDOR, trim(d.model) as model, 
from
  table1 pi,
  table2 d,
  table3c
where
  pi.id = d.id and
  pi.circuit_id = c.circuit_id 
  and ((trim(d.model) not in ('TA5000','TA5004','TA5006','TA1248','TA1248V')) 
or (  (trim(d.model) not in ('C7','E7') or trim(d.model) not like '%E3-48CR2%' or trim(d.model) not like '%E3-48R2%') ) )
order by d.VENDOR

当我尝试count(pi.port)时,得到ORA-00937:不是单组分组函数。如何获得供应商订购的端口数?

1 个答案:

答案 0 :(得分:0)

SELECT中所有未聚合的列都必须属于GROUP BY子句。

因此,您不需要DISTINCT,因为GROUP BY仍会返回不同的值。

在您的查询中,应该是

select 
  count(pi.port), 
  pi.RACK, pi.SHELF, pi.SLOT, pi.PORT, pi.BROADBAND_CIRCUIT_ID,   --> put all those
  d.DSLAM, d.VENDOR, trim(d.model)                                --> into GROUP BY
from ...
group by 
  pi.RACK, pi.SHELF, pi.SLOT, pi.PORT, pi.BROADBAND_CIRCUIT_ID, 
  d.DSLAM, d.VENDOR, trim(d.model)

[编辑,以表明这样的GROUP BY实际上有效]

数据并不重要;我懒于创建一个 smarter 测试用例(因为您也不介意发布自己的测试用例)。只是为了表明查询不会引发您所说的错误。

SQL> with
  2  table1 (id, port, rack, shelf, slot, broadband_circuit_id, circuit_id) as
  3    (select 1, 1, 1, 1, 1, 1, 1 from dual),
  4  table2 (id, model, vendor, dslam) as
  5    (select 1, 1, 1, 1 from dual),
  6  table3 (circuit_id) as
  7    (select 1 from dual)
  8  -- query goes here
  9  select
 10    count(pi.port) cnt,
 11    pi.RACK, pi.SHELF, pi.SLOT, pi.PORT, pi.BROADBAND_CIRCUIT_ID,   
 12    d.DSLAM, d.VENDOR, trim(d.model)
 13  -- your FROM clause
 14  from
 15    table1 pi,
 16    table2 d,
 17    table3 c
 18  where
 19    pi.id = d.id and
 20    pi.circuit_id = c.circuit_id
 21    and ((trim(d.model) not in ('TA5000','TA5004','TA5006','TA1248','TA1248V'))
 22  or (  (trim(d.model) not in ('C7','E7') or trim(d.model) not like '%E3-48CR2%' or trim(d.model)
 not like '%E3-48R2%') ) )
 23  -- my GROUP BY clause
 24  group by
 25    pi.RACK, pi.SHELF, pi.SLOT, pi.PORT, pi.BROADBAND_CIRCUIT_ID,
 26    d.DSLAM, d.VENDOR, trim(d.model)
 27  order by d.VENDOR;

       CNT       RACK      SHELF       SLOT       PORT BROADBAND_CIRCUIT_ID      DSLAM     VENDOR T
---------- ---------- ---------- ---------- ---------- -------------------- ---------- ---------- -
         1          1          1          1          1                    1          1          1 1

SQL>