SQL> with test (name, cnt, datum) as
2 (select 'Blue', 2, date '2022-11-01' from dual union all
3 select 'Blue', 1, date '2022-11-03' from dual union all
4 select 'Blue', 3, date '2022-11-11' from dual union all
5 select 'Green',5, date '2022-11-01' from dual union all
6 select 'Green',5, date '2022-11-11' from dual
7 )
质询:
8 select name,
9 sum(cnt) as cnt,
10 to_char(datum, 'Monyyyy', 'nls_date_language = english') datum
11 from test
12 group by name, to_char(datum, 'Monyyyy', 'nls_date_language = english');
NAME CNT DATUM
----- ---------- ----------------
Blue 6 Nov2022
Green 10 Nov2022
SQL>
WITH
tbl (A_NAME, A_NUMBER, A_DATE) AS
(
Select 'Black', 3, To_Date('01.11.2021', 'dd.mm.yyyy') From Dual Union All
Select 'Black', 1, To_Date('03.11.2021', 'dd.mm.yyyy') From Dual Union All
--
Select 'Blue', 2, To_Date('01.11.2022', 'dd.mm.yyyy') From Dual Union All
Select 'Blue', 1, To_Date('03.11.2022', 'dd.mm.yyyy') From Dual Union All
Select 'Blue', 3, To_Date('11.11.2022', 'dd.mm.yyyy') From Dual Union All
--
Select 'Greeen', 5, To_Date('01.11.2021', 'dd.mm.yyyy') From Dual Union All
--
Select 'Green', 5, To_Date('01.11.2022', 'dd.mm.yyyy') From Dual Union All
Select 'Green', 5, To_Date('11.11.2022', 'dd.mm.yyyy') From Dual
)
基本答案是使用group by进行聚合:
SELECT A_NAME, Sum(A_NUMBER) "CNT", To_Char(A_DATE, 'Mon yyyy') "A_DATE"
FROM tbl
GROUP BY A_NAME, To_Char(A_DATE, 'Mon yyyy')
此代码的结果数据集根本没有排序,Oracle可以按任何顺序返回结果。结果如下:
-- NO ORDER BY
A_NAME CNT A_DATE
------ ---------- --------
Black 4 Nov 2021
Green 10 Nov 2022
Blue 6 Nov 2022
Green 5 Nov 2021
-- ORDER BY A_NAME
A_NAME CNT A_DATE
------ ---------- --------
Black 4 Nov 2021
Blue 6 Nov 2022
Green 5 Nov 2021
Green 10 Nov 2022
-- ORDER BY A_DATE
A_NAME CNT A_DATE
------ ---------- --------
Black 4 Nov 2021
Green 5 Nov 2021
Blue 6 Nov 2022
Green 10 Nov 2022
-- ORDER BY A_DATE, A_NAME
A_NAME CNT A_DATE
------ ---------- --------
Black 4 Nov 2021
Green 5 Nov 2021
Blue 6 Nov 2022
Green 10 Nov 2022
-- ORDER BY A_DATE DESC, A_NAME
A_NAME CNT A_DATE
------ ---------- --------
Blue 6 Nov 2022
Green 10 Nov 2022
Black 4 Nov 2021
Green 5 Nov 2021
...您甚至可以按结果SUM()排序
-- ORDER BY Sum(A_NUMBER) DESC
A_NAME CNT A_DATE
------ ---------- --------
Green 10 Nov 2022
Blue 6 Nov 2022
Green 5 Nov 2021
Black 4 Nov 2021
3条答案
按热度按时间xytpbqjk1#
它是一个
sum
函数,而其他值是name和date(格式如您所愿)。样本数据:
质询:
kqqjbcuj2#
我假设您有一个名为“my_table”的表,其中字段my_name为字符串,my_date为数据。
这将为您提供以下结果。
对日期使用此格式更好,因为它按正确的顺序排序。
这可以在SQL Fiddle中测试。
vsmadaxz3#
关于行排序的讨论,这里有一个更大的示例数据集:
基本答案是使用group by进行聚合:
此代码的结果数据集根本没有排序,Oracle可以按任何顺序返回结果。结果如下:
如果您希望结果按特定顺序(ASC [默认值]或DESC),则应使用ORDER BY定义它。以下是几种可能性:
...您甚至可以按结果SUM()排序