如何获取按工作日排序的sql查询

Posted

技术标签:

【中文标题】如何获取按工作日排序的sql查询【英文标题】:How to get the sql query sorted by Weekday 【发布时间】:2020-01-08 11:08:18 【问题描述】:

我需要在元数据库中获取一个表,其中行对应于调度编号,而列是星期几。

我的 sql 代码是

SELECT 
    to_char( date_trunc('day',delivery_date_end) , 'Dy') as week,
    (dispatch_no)::int,
    (COUNT(DISTINCT delivery_id) FILTER (WHERE (date_part('epoch',delivery_date_end)::int >= date_part('epoch',delivered_at)::int)) / COUNT(DISTINCT delivery_id)::float) * 100 AS not_late

FROM sale_b2c
WHERE 
    delivery_date_end IS NOT NULL AND 
    status = 'Delivered' AND 
    delivered_at IS NOT NULL AND 
    city AND 
    delivery_date AND
    hub AND
    dispatch_no IS NOT NULL AND
    dispatch_no !='1.0'

GROUP BY  1,2
ORDER BY 2

在元数据库中旋转表后,输出看起来像这样

Dispatch No | Fri | Mon | Sat | Sun | Thu | Tue | Wed |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1           | a1  |  a2 | a3  | a4  | a5  | a6  | a7  |
2           | b1  |  b2 | b3  | b4  | b5  | b6  | b7  |
3           | c1  |  c2 | c3  | c4  | c5  | c6  | c7  | 
4           | d1  |  d2 | d3  | d4  | d5  | d6  | d7  | 
5           | e1  |  e2 | e3  | e4  | e5  | e6  | e7  |

我无法想出一种方法来按工作日的正确顺序对该输出进行排序。 我尝试使用

ORDER BY 2,1  

但它总是抛出错误。 在某些情况下,它也无法在尝试 ORDER By 时使用 week。

如何以适当的工作日格式对查询进行排序?

【问题讨论】:

您确定您正在运行 mysql 吗?这看起来不像 MySQL 语法(可能是 Postgres)。 您希望工作日的顺序是周一、周二、周三、周四、周五吗? @AlexMaina 是的。 你想要的输出是什么? 只是相同的输出,但工作日排序为周一、周二、周三、周四、周五、周六、周日@a_horse_with_no_name 【参考方案1】:

为什么不在 Postgres 中旋转数据?

SELECT dispatch_no,
       MAX(not_late) FILTER (WHERE week = 'Mon') as mon,
       MAX(not_late) FILTER (WHERE week = 'Tue') as tue,
       MAX(not_late) FILTER (WHERE week = 'Wed') as wed,
       MAX(not_late) FILTER (WHERE week = 'Thu') as thu,
       MAX(not_late) FILTER (WHERE week = 'Fri') as fri,
       MAX(not_late) FILTER (WHERE week = 'Sat') as sat,
       MAX(not_late) FILTER (WHERE week = 'Sun') as sun
FROM (SELECT to_char( date_trunc('day',delivery_date_end) , 'Dy') as week,
             (dispatch_no)::int,
             (COUNT(DISTINCT delivery_id) FILTER (WHERE (date_part('epoch',delivery_date_end)::int >= date_part('epoch',delivered_at)::int)) / COUNT(DISTINCT delivery_id)::float) * 100 AS not_late    
      FROM sale_b2c
      WHERE delivery_date_end IS NOT NULL AND 
            status = 'Delivered' AND 
            delivered_at IS NOT NULL AND 
            city AND 
            delivery_date AND
            hub AND
            dispatch_no IS NOT NULL AND
            dispatch_no <> '1.0'
      GROUP BY 1,2
     ) w
GROUP BY 1
ORDER BY 2

【讨论】:

它不起作用@Gordon。表格的列变为百分比值。这应该是每个单元格中的值。运行您的代码用空值填充表格

以上是关于如何获取按工作日排序的sql查询的主要内容,如果未能解决你的问题,请参考以下文章

Sql 查询以获取最多 10 条的最新记录并按提到行排名的字段排序 [关闭]

如何在 Oracle SQL 上进行查询以获取时间间隔,按特定字段分组

如何以正确的顺序链接查询集,而不是按日期排序,按foreignKey排序?

登录按钮按下后,如何获取Tkinter entry的值并传递给SQL查询?

在SQL查询中获取排序位置

如何获取 JPA 生成的 SQL 查询?