在第一次查询结果时添加CDept_Id

时间:2016-09-21 06:29:24

标签: sql sql-server sql-server-2005

在我的第一个查询中,我想获得CDept_Id。但CDept_Id表中不存在inward_doc_tracking_hdr列。

它来自inward_doc_tracking_trl表。如下所示

SELECT  CDept_id
FROM    inward_doc_tracking_trl
WHERE   ref_mkey IN ( SELECT    mkey
                      FROM      inward_doc_tracking_hdr
                      WHERE     doc_no = 'IW/HU/16/42' )

所以,从此。我得到CDept_Id。现在我想在下面的查询中添加它。

SELECT  mkey ,
        Delivered_By ,
        Department_Id ,
        ( SELECT    mkey
          FROM      erp190516.dbo.emp_mst
          WHERE     mkey IN ( SELECT    employee_mkey
                              FROM      erp190516.dbo.user_mst
                              WHERE     mkey = To_User )
        ) User_Id ,
        Doc_Type ,
        Email_Id ,
        Ref_No ,
        CONVERT(VARCHAR(25), Ref_date, 103) Ref_date ,
        Inward_Amt ,
        Remarks ,
        party_name ,
        disp_through
FROM    erp190516.dbo.inward_doc_tracking_hdr ,
        CDept_id  -- add CDept_id here
WHERE   doc_no = 'IW/HU/16/42'
        AND Status_Flag = '13'

如何添加此

更新

inward_doc_tracking_hdr mkey等于inward_doc_tracking_trl ref_mkey

1 个答案:

答案 0 :(得分:1)

它正在阅读魔术玻璃灯泡,但我认为您可能会使用INNER JOINmkey链接到另一张桌子ref_mkey作为链接:

Select hdr.mkey
      ,hdr.Delivered_By
      ,hdr.Department_Id 
      ,hdr.Doc_Type,Email_Id
      ,hdr.Ref_No
      ,convert(varchar(25),hdr.Ref_date,103) Ref_date
      ,hdr.Inward_Amt
      ,hdr.Remarks
      ,hdr.party_name
      ,hdr.disp_through
      ,trl.CDept_Id
from erp190516.dbo.inward_doc_tracking_hdr AS hdr
inner join erp190516.dbo.inward_doc_tracking_trl AS trl on hdr.mkey=trl.ref_mkey
 where hdr.doc_no = 'IW/HU/16/42'  
 and hdr.Status_Flag = '13'

更新......更加猜测......

- 获得CDept_Id分配顺序的第一个CTE

;WITH OrderedCDept AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY ref_mkey ORDER BY CDept_Id DESC) AS SortInx
          ,ref_mkey
          ,CDept_Id
    FROM erp190516.dbo.inward_doc_tracking_trl
)

- 使用TOP 1 WITH TIES来获取所有第一行行的第二次CTE

,LatestCDept AS
(
    SELECT TOP 1 WITH TIES *
    FROM OrderedCDept
    ORDER BY SortInx
)

- 现在使用第二个CTE而不是表来加入

Select hdr.mkey
      ,hdr.Delivered_By
      ,hdr.Department_Id 
      ,hdr.Doc_Type,Email_Id
      ,hdr.Ref_No
      ,convert(varchar(25),hdr.Ref_date,103) Ref_date
      ,hdr.Inward_Amt
      ,hdr.Remarks
      ,hdr.party_name
      ,hdr.disp_through
      ,trl.CDept_Id
from erp190516.dbo.inward_doc_tracking_hdr AS hdr
inner join LatestCDept AS trl on hdr.mkey=trl.ref_mkey
 where hdr.doc_no = 'IW/HU/16/42'  
 and hdr.Status_Flag = '13'