使用内联查询语句获取Count

时间:2017-05-05 10:04:41

标签: sql oracle oracle11g

我正在尝试从2个表中获取列数。我写了一个这样的SQL语句:

SELECT COUNT (assetnum) asset, COUNT (description) description, COUNT ( CASE WHEN totdowntime > 0 THEN assetnum END) totdowntime, (SELECT COUNT (wonum) FROM workorder WHERE assetnum IN (SELECT assetnum FROM asset WHERE TO_CHAR (installdate,'YYYY') ='2011' ) ) AS wo_count FROM asset WHERE TO_CHAR (installdate, 'YYYY') = '2011

我不明白为什么即使内联语句返回单个值,上面的代码也不起作用?

数据是这样的:

资产表:

assetnum   description  totdowntime  insatlldate   siteid
1000        ABC         1            01-01-2011    AGN
1001        DEF         1.5          02-01-2011    AGN
1002        AKK         5            03-01-2011    AGN
1003        LSDL        3            04-01-2011    AGN
1004        JKDF        3.3          01-02-2012    AGN
1005        DFJK        4.5          01-02-2012    AGN

工单表:

wonum   siteid  assetnum
  1      AGN    1000
  2      AGN    1001
  3      AGN    1002
  4      DVN    1000
  5      DVN    1001
  6      AGN    1004

期望的输出:

asset_cnt   descrpition_cnt totdowntime_cnt wonum_cnt
    6          6             6                4

我得到的输出:

Error:ORA-00937: not a single-group group function

2 个答案:

答案 0 :(得分:1)


您可以使用以下查询,

SELECT COUNT (A.assetnum) AS asset, COUNT (A.description) AS description,
COUNT ( A.totdowntime) AS totdowntime,
COUNT (AN.wonum)
FROM asset A
INNER JOIN workorder AN
ON (A.assetnum  = AN.assetnum )

WH_ TO_CHAR(A.installdate,' YYYY')=' 2011';

根据表A或AN使用installdate的别名 您可以使用需要的案例

COUNT (CASE WHEN A.totdowntime > 0 THEN A.assetnum END)

答案 1 :(得分:0)

我怀疑你想要这个:

SELECT COUNT(a.assetnum) as asset,
       COUNT(a.description) as description,
       SUM(CASE WHEN a.totdowntime > 0 AND a.assetnum IS NOT NULL THEN 1 ELSE 0 
           END) as totdowntime,
       (SELECT COUNT(wo.wonum)
        FROM workorder wo
        WHERE wo.assetnum = a.assetnum
       ) as wo_count
FROM asset a
WHERE installdate >= DATE '2011-01-01' AND
      installdate < DATE '2012-01-01';

注意:

  • 前两个COUNT()可能会返回相同的值。请记住,COUNT()计算非NULL值的数量。
  • 我更喜欢SUM()而不是COUNT()来计算表达式中的值。但COUNT()也没问题。
  • 我认为你需要一个相关的子查询来计算workorder
  • 表别名和限定列名称在任何查询中都是个好主意。