Select

使用組中的值選擇同一組中的所有值

  • November 1, 2018

我有以下查詢:

SELECT
   SubstitutionGroupID,
   Material.Number,
   Material.DescriptionEN
FROM
   MaterialSubstitution
   INNER JOIN Material on Material.MaterialID = MaterialSubstitution.MaterialID
ORDER BY
   SubstitutionGroupID, Material.Number

結果範例:

SubstitutionGroupID Number      DescriptionEN
52494               303H603021  HINGE R
52494               3H603020    HINGE R
52495               303H604031  TRAY EJECT
52495               3H604030    TRAY EJECT (1/2)

我想要一個查詢,我可以在其中定義一個數字並在一個 SubstitutionGroupID 中接收所有數字。

如果我了解您的要求,我相信這就是您所追求的:

DECLARE @Number NVARCHAR(30);
SET @Number = '3H603020';

SELECT
   ms.SubstitutionGroupID,
   subs.Number,
   subs.DescriptionEN
FROM
   MaterialSubstitution AS ms
   INNER JOIN Material  AS m ON m.MaterialID = ms.MaterialID
   INNER JOIN Material  AS subs ON subs.MaterialID = ms.MaterialID
WHERE
   m.Number = @Number
ORDER BY
   ms.SubstitutionGroupID, subs.Number

您需要Material再次加入以找到給定的“替換”(因此是別名subsMaterial.Number

引用自:https://dba.stackexchange.com/questions/192685