我需要创建一个查询,该查询将显示按类型排序的每天插入的查询量。这听起来很模糊,所以我将在下面演示:
+----+------+----------+
| 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
但是这给了我重复的日期/类型组合。这就是它的回报:
答案 0 :(得分:2)
按type
分组,按天分组(即TRUNC( inserted )
):
Oracle安装程序:
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
答案 1 :(得分:0)
这对你有用吗?
select type, inserted, count(inserted)
from tmp_table
group by type, inserted