sql - SQL returning two rows matching different criteria into separate columns
问题描述
I'm having trouble adjusting an SQL query where I need to take two rows that match similar criteria and give them each a column. Here is an example of the table I am querying:
SEQNO | PICKSLIPNO | EVENT_TYPE | DATETIME | SUBJECT |
---|---|---|---|---|
20000 | 10045 | H | 2021-09-30 8:21 | Picking Slip Created |
20001 | 10045 | P | 2021-09-30 8:22 | |
20002 | 10045 | I | 2021-09-30 8:25 | |
20003 | 10045 | H | 2021-09-30 11:22 | Order delivered |
And the result I would like:
PICKSLIPNO | PickingDate | DeliveryDate |
---|---|---|
10045 | 2021-09-30 8:21 | 2021-09-30 11:22 |
10052 | 2021-09-30 8:25 | 2021-09-30 10:32 |
10122 | 2021-09-30 7:32 | 2021-09-30 13:54 |
I am trying query and return both the datetimes of picking slip creation and order delivery in two separate columns on the same row for each pickingslipno between a certain date range. I've tried the following code which worked perfectly when I only query one PickslipNo. However, as soon as I try querying a wider range I get an error that my subqueries are returning multiple results.
SELECT (
SELECT DATETIME
FROM SALESORDHIST
WHERE SUBJECT LIKE 'Picking Slip Created'
AND DATETIME >= GETDATE()-5
AND DATETIME <= GETDATE()
) AS PickingDate,
(
SELECT DATETIME
FROM SALESORDHIST
WHERE SUBJECT LIKE 'Order delivered'
AND DATETIME >= GETDATE()-5
AND DATETIME <= GETDATE()
) AS DeliveryDate
FROM SALESORDHIST
Apologies if this doesn't make sense and I appreciate you taking the time to read this/help out.
解决方案
First select the data for the order slip create and then left join to the delivery -- like this:
SELECT SLIP.PICKSLIPNO , SLIP.DATETIME AS PickingDate, DEL.DATETIME as DeliveryDate
FROM SALESORDHIST SLIP
LEFT JOIN SALESORDHIST DEL ON SLIP.PICKSLIPNO = DEL.PICKSLIPNO
AND DEL.SUBJECT LIKE 'Order delivered'
WHERE SLIP.SUBJECT LIKE 'Picking Slip Created'
推荐阅读
- ffmpeg - pyav / libav / ffmpeg 当来自实时源的帧处理速度不够快时会发生什么
- c++ - 继承的静态工厂方法返回子类类型
- github-for-windows - Windows 上的 github 运行程序在 PowerShell 上找不到可执行文件
- docker - 无法通过 socks5 代理访问 docker 容器中的 10.0.0.0
- python - Python 抽象类和多重继承
- python - ubuntu pygame 窗口没有显示
- html - 如何使用 #anchor 触发 javascript 脚本
- java - 如何按对象的枚举属性对地图进行排序
- c# - 如何过滤列表类型的属性
使用 odata - binary - 来自二叉树的二元奖励