我正在iReport中创建一个报告。我正在使用postgresql9.2数据库。尝试基于另一个字段创建求和。首先,我按车辆编号逐个字段创建报表,然后创建一个变量,尝试在此字段中按组逐个求和。
我的报告结果
vh_name | va_date | trip_no |
Vehicle-01 | 2019-01-15 | 1 |
Vehicle-01 | 2019-01-15 | 1 |
Vehicle-01 | 2019-01-16 | 1 |
-----------+------------+---------+
Vehicle-02 | 2019-01-17 | 1 |
Vehicle-02 | 2019-01-18 | 1 |
Vehicle-02 | 2019-01-19 | 1 |
-----------+------------+---------+
Vehicle-03 | 2019-01-17 | 1 |
Vehicle-03 | 2019-01-17 | 1 |
Vehicle-03 | 2019-01-17 | 1 |
Vehicle-03 | 2019-01-18 | 1 |
-----------+------------+---------+
我的预期结果
vh_name | va_date | trip_no | total_trip |
Vehicle-01 | 2019-01-15 | 1 | |
Vehicle-01 | 2019-01-15 | 1 | 3 |
Vehicle-01 | 2019-01-16 | 1 | |
-----------+------------+---------+-------------
Vehicle-02 | 2019-01-17 | 1 | |
Vehicle-02 | 2019-01-18 | 1 | 3 |
Vehicle-02 | 2019-01-19 | 1 | |
-----------+------------+---------+-------------
Vehicle-03 | 2019-01-17 | 1 | |
Vehicle-03 | 2019-01-17 | 1 | |
Vehicle-03 | 2019-01-17 | 1 | 4 |
Vehicle-03 | 2019-01-18 | 1 | |
-----------+------------+---------+-------------
答案 0 :(得分:1)
基于Using SUM() without grouping the results,您的SQL应该看起来像这样:
SELECT vh_name, va_dat, trip_no, SUM(trip_sum.amount) as trip_sum
FROM my_trips
CROSS JOIN (
SELECT SUM(amount) as amount FROM my_trips AS amount
GROUP BY vh_name) trip_sum
请注意,唯一计数可能更容易(如果trip_no始终为1):
SELECT vh_name, va_dat, trip_no, COUNT(DISTINCT vh_name) as amount
FROM my_trips