SQL如何查询总计&;小计
我有一个如下表,其中存储了日期、订单id和订单类型SQL如何查询总计&;小计,sql,vertica,subtotal,Sql,Vertica,Subtotal,我有一个如下表,其中存储了日期、订单id和订单类型 select day, order_id, order_type from sample_table 白天 订单号 订单类型 2021-03-01 1. 离线 2021-03-01 2. 离线 2021-03-01 3. 在线 的 2021-03-01 4. 在线 的 2021-03-01 5. 离线 2021-03-01 6. 离线 2021-03-02 7. 在线 的 2021-03-02 8. 在线 的 2021-03-02 9 离线
select day, order_id, order_type
from sample_table
白天
订单号
订单类型
2021-03-01
1.
离线
2021-03-01
2.
离线
2021-03-01
3.
在线 的
2021-03-01
4.
在线 的
2021-03-01
5.
离线
2021-03-01
6.
离线
2021-03-02
7.
在线 的
2021-03-02
8.
在线 的
2021-03-02
9
离线
2021-03-02
10
离线
2021-03-03
11
离线
2021-03-03
12
离线
使用
案例
和总和
:
select day,
count(1) as total_order
sum(case when order_type='offline' then 1 end) as num_offline_order,
sum(case when order_type='online' then 1 end) as num_online_order
from sample_table
group by day
order by day
你需要以数据为中心。在Vertica中实现条件聚合的一种简单方法是使用
:
:
select day, count(*) as total_order,
sum( (order_type = 'online')::int ) as num_online,
sum( (order_type = 'offline')::int ) as num_offline
from t
group by day;
您还可以使用
count
来聚合非空值
select
day,
count(*) as total_order,
count(case when order_type='offline' then 1 else null end) as offline_orders,
count(case when order_type='online' then 1 else null end) as online_orders
from sample_table
group by day
order by day;
我喜欢你的简洁:简单地将布尔值转换为INT,得到0对1的计数器,然后求和。