2017-02-15 103 views
1

我需要創建一個查詢,該查詢將顯示每天按類型排序的查詢插入量。這聽起來很模糊,所以我將在下面演示一下:每個類型每天計算插入的行數

+----+------+----------+ 
| id | type | inserted | 
+----+------+----------+ 
| 1 | a | 1/2/2017 | 
| 2 | a | 1/2/2017 | 
| 3 | a | 2/2/2017 | 
| 4 | b | 1/2/2017 | 
| 5 | b | 1/2/2017 | 
| 6 | b | 2/2/2017 | 
| 7 | b | 3/2/2017 | 
| 8 | b | 3/2/2017 | 
+----+------+----------+ 

結果必須是:

+------+----------+--------+ 
| type | date | amount | 
+------+----------+--------+ 
| a | 1/2/2017 |  2 | 
| a | 2/2/2017 |  1 | 
| b | 1/2/2017 |  2 | 
| b | 2/2/2017 |  1 | 
| b | 3/2/2017 |  2 | 
+------+----------+--------+ 

我已經嘗試過用GROUP BY和DISTINCT一些查詢,但我不能想出如何沒有重複。

我已經嘗試過: SELECT date, type, count(*) FROM table GROUP BY date, type但這給了我重複的日期/類型組合。這是它返回:

duplicates

+0

你能證明你試過了什麼嗎? – jjj

+0

可能重複的[使用多個列的組](http://stackoverflow.com/questions/2421388/using-group-by-on-multiple-columns) – Ivar

+0

我試過'SELECT date,type,count(*) FROM表GROUP BY日期,鍵入'但它具有重複的日期/類型組合。 –

回答

2

組由type並通過天(即TRUNC(inserted)):

甲骨文設置

CREATE TABLE your_table (id, type, inserted) AS 
    SELECT 1, 'a', TO_DATE('2017-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL UNION ALL 
    SELECT 2, 'a', TO_DATE('2017-02-01 01:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL UNION ALL 
    SELECT 3, 'a', TO_DATE('2017-02-02 00:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL UNION ALL 
    SELECT 4, 'b', TO_DATE('2017-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL UNION ALL 
    SELECT 5, 'b', TO_DATE('2017-02-01 01:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL UNION ALL 
    SELECT 6, 'b', TO_DATE('2017-02-02 01:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL UNION ALL 
    SELECT 7, 'b', TO_DATE('2017-02-03 02:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL UNION ALL 
    SELECT 8, 'b', TO_DATE('2017-02-03 03:00:00', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL; 

查詢

SELECT type, 
     TRUNC(inserted) AS "date", 
     COUNT(1) AS amount 
FROM your_table 
GROUP BY type, 
     TRUNC(inserted); 

輸出

TYPE date    AMOUNT 
---- ------------------- ------ 
a 2017-02-01 00:00:00  2 
a 2017-02-02 00:00:00  1 
b 2017-02-01 00:00:00  2 
b 2017-02-02 00:00:00  1 
b 2017-02-03 00:00:00  2 
+0

不是一個GROUP BY表達式 –

+0

@LuudvanKeulen您是否按鍵入運行它?它適用於Oracle 11gR2。 – MT0

+0

'選擇incumbtend with group by' –

0

是爲你工作?

select type, inserted, count(inserted) 
    from tmp_table 
    group by type, inserted 
+0

SQL Developer無法識別'[]'標籤。 –

+0

方括號不是有效的oracle語法。 – MT0

+0

我試圖在MS SQL服務器....刪除括號 – Kostis