选择Count of Distinct rows和sum

时间:2017-05-02 23:49:05

标签: sql oracle

我有一个看起来像这样的表:

Item     |     Document
-----------------------
Book     |      BL
Book     |      CT
Book     |      OP
Pen      |      CT
Pen      |      BL
Mug      |      OP

我需要获取所有唯一项目的计数以及该表中所有文档的计数。对于上面的示例,我正在寻找这样的输出:

3        |     6

3 - Book, Pen, Mug
6 - total count of available documents

我的SQL看起来像这样:

 SELECT ITEM , COUNT (*) AS DOC_COUNT
    FROM TABL1
  GROUP BY ITEM
  HAVING COUNT (*) > 0

但我只获得所有项目的列表及其文档数量。 有人可以帮我弄清楚如何解决这个问题吗?谢谢!

3 个答案:

答案 0 :(得分:4)

小学,亲爱的沃森。

public String readLineTimeout(BufferedReader reader, long timeout) throws TimeoutException, IOException {
    long start = System.currentTimeMillis();

    while (!reader.ready()) {
        if (System.currentTimeMillis() - start >= timeout)
            throw new TimeoutException();

        // optional delay between polling
        try { Thread.sleep(50); } catch (Exception ignore) {}
    }

    return reader.readLine(); // won't block since reader is ready
}

答案 1 :(得分:2)

请尝试

SELECT * FROM table1;
SELECT item ,
  MAX(ITEMS_)ITEM,
  MAX(DOC_)DOC,
  MAX(ro_num)TOTAL_ITEM
FROM
  (SELECT item,
    row_number() over (partition BY ITEM order by ITEM DESC)ITEMS_,
    row_number() over (partition BY document order by document DESC ) DOC_,
    MAX(rownum) over (partition BY 1)ro_num
  FROM table1
  )
GROUP BY item

答案 2 :(得分:0)

如果您的预期输出是

curl 'http://localhost:8983/solr/UMB/replication?command=restore&name=2017xxxxxxxxx'

请尝试以下查询

3        |     6

3 - Book, Pen, Mug
6 - total count of available documents

您也可以使用ROLLUP

SELECT TO_CHAR (COUNT (DISTINCT item)) AS item_count, 
       TO_CHAR (COUNT (document)) AS doc_count 
  FROM (SELECT item, document FROM table1) 
UNION ALL 
SELECT    COUNT (item) 
       || ' - ' 
       || LISTAGG (item, ',') WITHIN GROUP (ORDER BY item) 
          items, 
       NULL 
  FROM (SELECT DISTINCT item 
          FROM ( (SELECT item, document FROM table1))) 
UNION ALL 
SELECT COUNT (document) || ' - total count of available documents' document, 
       NULL 
  FROM (SELECT document 
          FROM ( (SELECT item, document FROM table1))) 

Example