sql—如何高效地从同一个表中的不同列和行返回数据?

x0fgdtte  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(309)

我有一个交易表,如下所示,显示产品正在生产,然后删除,因为他们被扫描到一个订单。我想显示两个产品,已经和还没有扫描到一个订单,没有列出表中的每一笔交易。我从1秒的简单选择,变成了10分钟的选择和一个子查询。
有没有更好的方法让我这么做?
我正在运行microsoft sql server 2017,无法修改表结构,因为它链接到专有生产系统。我不相信我可以聚合,因为还有其他文本字段要返回。

选择子查询(非常慢)

SELECT
    Unique,
    Weight,
    ProductionDate,
    ProductCode,
    (
        SELECT OrderNumber
        FROM Table AS B
        WHERE
            B.Unique = A.Unique
    ) AS OrderNumber
FROM Table AS A

源表

+----------+-----------+-------------------------+-------------+-------------+
|  Unique  |  Weight   |     ProductionDate      | OrderNumber | ProductCode |
+----------+-----------+-------------------------+-------------+-------------+
| 14962904 |  1.920000 | 2020-06-05 11:43:12.000 |             | ABC123      |
| 14962905 |  1.990000 | 2020-06-05 11:43:14.000 |             | ABC123      |
| 14962906 |  2.020000 | 2020-06-05 11:43:20.000 |             | ABC123      |
| 14962909 |  2.030000 | 2020-06-05 11:45:09.000 |             | ABC123      |
| 14962909 | -2.030000 | 2020-06-05 11:45:09.000 |      431723 | ABC123      |
| 14962910 |  2.020000 | 2020-06-05 11:45:15.000 |             | ABC123      |
| 14962910 | -2.020000 | 2020-06-05 11:45:15.000 |      431723 | ABC123      |
| 14962911 |  1.990000 | 2020-06-05 11:45:24.000 |             | ABC123      |
| 14962911 | -1.990000 | 2020-06-05 11:45:24.000 |      431723 | ABC123      |
+----------+-----------+-------------------------+-------------+-------------+

期望的结果

+----------+-----------+-------------------------+-------------+-------------+
|  Unique  |  Weight   |     ProductionDate      | OrderNumber | ProductCode |
+----------+-----------+-------------------------+-------------+-------------+
| 14962904 |  1.920000 | 2020-06-05 11:43:12.000 |             | ABC123      |
| 14962905 |  1.990000 | 2020-06-05 11:43:14.000 |             | ABC123      |
| 14962906 |  2.020000 | 2020-06-05 11:43:20.000 |             | ABC123      |
| 14962909 |  2.030000 | 2020-06-05 11:45:09.000 |      431723 | ABC123      |
| 14962910 |  2.020000 | 2020-06-05 11:45:15.000 |      431723 | ABC123      |
| 14962911 |  1.990000 | 2020-06-05 11:45:24.000 |      431723 | ABC123      |
+----------+-----------+-------------------------+-------------+-------------+
brvekthn

brvekthn1#

我可能睡过头了ù但从您的数据来看,这看起来确实像是聚合:

select 
    unique,
    max(weight) weight,
    productionDate,
    max(orderNumber) orderNumber
from mtable t
group by unique, productionDate

相关问题