SQL连接两个表并检索数据

时间:2019-01-26 18:58:52

标签: mysql sql-server

表1-缺陷

Defect ID | Name             | Type
--------------------------------
SB001     | Light Bead       | Bead
SB002     | Narrow Bead      | Bead
SB003     | ROUND BEAD       | Bead
SB004     | O`RING LEAK      | Bead
C0001     | Spread cord      | GT
C0002     | Sidewall wrinkle | GT

表2-轮胎缺陷

Tyre S/N   | DEFECT ID | Datetime
------------------------------
0108160020 | SB004     | 2019-01-09 21:43:01.293
2512160005 | SB003     | 2019-01-10 00:05:29.150
3010160003 | SB004     | 2019-01-11 00:05:29.150

我需要类似下面的结果

Defect ID  | Defect Name | Type
------------------------
SB004      | O`RING LEAK | BEAD
SB003      | ROUND BEAD  | BEAD
SB001      | Light Bead  | BEAD
SB002      | Narrow Bead | BEAD

我想首先得到经常获得缺陷的缺陷,而其他缺陷是 按名称或其他顺序订购

谢谢帮助我。...

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT
    DF.[Defect ID],
    DF.[Name],
    DF.[Type],
    COUNT(DF.*) AS [Defect count]
FROM
    DEFECT AS DF
    LEFT JOIN
    [Tyres Defect] AS TD
    ON DF.[Defect ID] = TD.[Defect ID]
GROUP BY
    DF.[Defect ID],
    [Name],
    [Type]
ORDER BY
    COUNT(DF.[Defect ID]) DESC
    DF.[Name]

还将为您提供每种缺陷类型的数量。 (这是sql-server

的答案