我使用的是Oracle 12c,需要有关简单查询的帮助。
以下是我目前所拥有的样本数据:
Table Name: customer
表DDL
create table customer(
customer_id varchar2(50),
name varchar2(50),
activation_dt date,
space_occupied number(50)
);
样本表数据:
customer_id name activation_dt space_occupied
abc abc-001 2016-09-12 20
xyz xyz-001 2016-09-12 10
示例数据输出
我正在寻找的查询将提供以下内容:
customer_id name activation_dt space_occupied
abc abc-001 2016-09-12 20
xyz xyz-001 2016-09-12 10
Total_Space null null 30
答案 0 :(得分:1)
使用分组函数ROLLUP()
,这是一种稍微有点hack-y的方法。 Find out more。
SQL> select coalesce(customer_id, 'Total Space') as customer_id
2 , name
3 , activation_dt
4 , sum(space_occupied) as space_occupied
5 from customer
6 group by ROLLUP(customer_id, name, activation_dt)
7 having grouping(customer_id) = 1
8 or (grouping(name) + grouping(customer_id)+ grouping(activation_dt)) = 0;
CUSTOMER_ID NAME ACTIVATIO SPACE_OCCUPIED
------------ ------------ --------- --------------
abc abc-001 12-SEP-16 20
xyz xyz-001 12-SEP-16 10
Total Space 30
SQL>
ROLLUP()
为每个列组合生成中间总计;详细HAVING
子句将其过滤掉并仅保留总计。
答案 1 :(得分:0)
你想要的是有点不寻常,好像customer_id是整数,然后你必须把它转换为字符串等,但这是你的要求,然后如果这样实现。
SELECT customer_id,
name,
activation_dt,
space_occupied
FROM
(SELECT 1 AS seq,
customer_id,
name,
activation_dt,
space_occupied
FROM customer
UNION ALL
SELECT 2 AS seq,
'Total_Space' AS customer_id,
NULL AS name,
NULL AS activation_dt,
sum(space_occupied) AS space_occupied
FROM customer
)
ORDER BY seq
说明:
1 as seq
来1
使用您的客户结果集进行硬编码。 2 as seq
Total_Space
。输出
+-------------+---------+---------------+----------------+
| CUSTOMER_ID | NAME | ACTIVATION_DT | SPACE_OCCUPIED |
+-------------+---------+---------------+----------------+
| abc | abc-001 | 12-SEP-16 | 20 |
| xyz | xyz-001 | 12-SEP-16 | 10 |
| Total_Space | null | null | 30 |
+-------------+---------+---------------+----------------+
答案 2 :(得分:0)
似乎是一个使用group by grouping sets
的好地方,这似乎是他们的设计目的。 Doc link
SELECT coalesce(Customer_Id,'Total_Space') as Customer_ID
, Name
, ActiviatioN_DT
, sum(Space_occupied) space_Occupied
FROM customer
GROUP BY GROUPING SETS ((Customer_ID, Name, Activation_DT, Space_Occupied)
,())
这里的关键是我们总结占用的空间。两种不同的分组机制告诉引擎保持每一行的原始形式和1条记录与space_occupied相加;因为我们分组by()空集;只返回聚合值;与常量一起(合并硬编码的值!)
这样做的好处在于,如果您需要按其他内容进行分组,则可以使用多个分组集。想象一下具有产品部门,团队和生产线的材料,我希望按部门,组和生产线分析销售总额。您可以简单地按()分组以获得总计,(product_division,Product_Group,line)以获得产品系列(product_Divsion,product_group)以获得product_group总计和(product_division)以获得产品分部总计。对于部分立方体生成而言非常强大的东西。