【发布时间】:2021-03-21 15:31:32
【问题描述】:
假设我有一个名为 orders 的表,如下所示:
| id | order date | Orders_Wanted | Orders_Given |
|---|---|---|---|
| 1 | 2020-11-29 19:12:44.417 | 2 | 6 |
| 1 | 2020-11-29 20:12:44.417 | 2 | 6 |
| 1 | 2020-11-30 23:37:28.692 | 8 | 2 |
| 1 | 2020-11-30 23:37:28.692 | 2 | 6 |
如何编写一个查询,显示 orders_wanted - orders_given 的计数,按小时分为两列,一列计算正面结果,另一列计算负面结果(请注意,orders_wanted 和 orders_given 是时间,这就是为什么我正在计算 orders_wanted - orders_given)。我还想添加最后一列,用于计算每小时总订单数为正数的百分比 (count_orders_positive/ (count_orders_negative + Count_orders_positive))。
查询的输出如下所示:
| week | day | hour | count_orders_positive | count_orders_negative | Percentage_orders_positive |
|---|---|---|---|---|---|
| 48 | 7 | 19 | 0 | 1 | 100% |
| 48 | 7 | 20 | 0 | 1 | 100% |
| 49 | 1 | 23 | 1 | 1 | 50% |
到目前为止,我能够使用这些查询获得最后两个结果,但我不知道如何组合它们。
SELECT
extract (week from (order_date at time zone 'MST' at time zone 'UTC') ) as "week",
extract (isodow from (order_date at time zone 'MST' at time zone 'UTC') ) as "day",
extract (hour from (order_date at time zone 'MST' at time zone 'UTC') ) as "hour",
Count (extract (hour from (order_date at time zone 'MST' at time zone 'UTC') )) as
"count_orders_positive"
from orders
WHERE orders_wanted - orders_given >= 0
group by week, day, hour
order by week, day, hour;
| week | day | hour | count_orders_positive |
|---|---|---|---|
| 49 | 1 | 23 | 1 |
SELECT
extract (week from (order_date at time zone 'MST' at time zone 'UTC') ) as "week",
extract (isodow from (order_date at time zone 'MST' at time zone 'UTC') ) as "day",
extract (hour from (order_date at time zone 'MST' at time zone 'UTC') ) as "hour",
Count (extract (hour from (order_date at time zone 'MST' at time zone 'UTC') )) as
"count_orders_negative"
from orders
WHERE orders_wanted - orders_given < 0
group by week, day, hour
order by week, day, hour;
| week | day | hour | count_orders_negative |
|---|---|---|---|
| 48 | 7 | 19 | 1 |
| 48 | 7 | 20 | 1 |
| 49 | 1 | 23 | 1 |
【问题讨论】:
-
你如何从
wanted == 2和given == 6得到count_positive == 1 -
@s-man 感谢您指出这一点。我的示例表出错了。我现在已经修好了。
标签: sql postgresql datatable count pivot