1

我一直在尝试查询一些信息,但我似乎无法提出查询。以下是表格信息和我当前的查询。

公司表:

+-----------+-----------+------------+
| CompanyID |  Address  | PostalCode |
+-----------+-----------+------------+
| a-coy     | 31 street |     111111 |
| b-coy     | 32 street |     111222 |
+-----------+-----------+------------+

维修表:

+----------+-----------+----------------+------------+----------+
| SerialNo | CompanyID | PersonInCharge | RepairDate | RepairBy |
+----------+-----------+----------------+------------+----------+
|    15000 | a-coy     | John           | 01-May-17  | Jason    |
|    15001 | a-coy     | John           | 02-May-17  | Jack     |
+----------+-----------+----------------+------------+----------+

我的目的是查询只有 1 个结果的最新维修工程条目。

我目前的查询如下:

SELECT 
    c.companyid, c.address, r.repairdate, r.repairby
FROM 
    company c 
INNER JOIN 
    repair r ON c.companyID = r.companyID
WHERE 
    c.companyid = 'a-coy'

我得到以下结果:

+-----------+-----------+------------+----------+
| CompanyID |  Address  | RepairDate | RepairBy |
+-----------+-----------+------------+----------+
| a-coy     | 31 street | 01-May-17  | Jason    |
| a-coy     | 31 street | 02-May-17  | Jack     |
+-----------+-----------+------------+----------+

但我想要的结果只是具有最新修复日期的条目,它看起来完全像这样:

+-----------+-----------+------------+----------+
| CompanyID |  Address  | RepairDate | RepairBy |
+-----------+-----------+------------+----------+
| a-coy     | 31 street | 02-May-17  | Jack     |
+-----------+-----------+------------+----------+
4

2 回答 2

2
SELECT TOP 1
c.companyid, 
c.address, 
r.repairdate,
r.repairby
FROM company c 
INNER JOIN repair r ON c.companyID=r.companyID
WHERE c.companyid = 'a-coy'
ORDER BY r.repairdate DESC
于 2017-05-29T08:31:57.080 回答
-1

一种选择是用于ROW_NUMBER()确定每家公司的最新维修日期。

SELECT
    t.companyid,
    t.address,
    t.repairdate,
    t.repairby
FROM
(
    SELECT
        c.companyid,
        c.address,
        r.repairdate,
        r.repairby,
        ROW_NUMBER() OVER (PARTITION BY c.companyid ORDER BY r.repairdate DESC) rn
    FROM company c
    INNER JOIN repair r
        ON c.companyID = r.companyID
) t
WHERE t.rn = 1 AND
      t.companyid = 'a-coy'

如果我们想获得不止一家公司的最新维修记录,这将是一个不错的选择。给出的另一个答案适用于一家公司,但不适用于一家以上的公司。

于 2017-05-29T08:33:32.130 回答