如何在SQL列中按天计算值的总和
我有一个如下表,其中存储了日期、客户名称和订单值/如何在SQL列中按天计算值的总和,sql,sum,vertica,calculation,Sql,Sum,Vertica,Calculation,我有一个如下表,其中存储了日期、客户名称和订单值/ select day, client_name, order_value from sample_table 白天 客户名称 订单价值 2021-01-01 A. 100 2021-01-01 A. 100 2021-01-02 A. 200 2021-01-03 A. 100 2021-01-01 B 300 2021-01-01 B 400 2021-01-01 C 500 2021-01-02 C 500 2021-01-02 C 50
select day, client_name, order_value
from sample_table
白天
客户名称
订单价值
2021-01-01
A.
100
2021-01-01
A.
100
2021-01-02
A.
200
2021-01-03
A.
100
2021-01-01
B
300
2021-01-01
B
400
2021-01-01
C
500
2021-01-02
C
500
2021-01-02
C
500
如果您知道天数,可以使用条件聚合:
select client_name,
sum(case when date = '2021-01-01' then order_value end) as date_20210101,
sum(case when date = '2021-01-02' then order_value end) as date_20210102,
sum(case when date = '2021-01-03' then order_value end) as date_20210103
from t
group by client_name ;
如果您不知道具体的日期(即,您希望它们基于数据或变量),那么您需要使用动态SQL。这意味着您将SQL语句构造为一个字符串,然后执行它。需要多少列??每年有365天谢谢你这就够了!