首页 > 解决方案 > 根据其他列中的几个条件选择数据行

问题描述

我正在使用 SQL Server,并且我有以下数据:

NO_PO_MYSAP ID_PLANNING_DETAIL ITEM BL
5501        13683              6    2019-11-28
5501        13683              7    2019-11-28
1101        13685              6    2019-12-10
1101        13685              6    2019-12-11
1101        13685              7    2019-12-10
1101        13685              7    2019-12-11

你可以看到他们有不同的号码。相同NO_PO_MYSAP下的行数,因为当我选择 distinct 时,13685BL具有不同的值。

我想要的是,如果BL在类似的 NO_PO_MYSAP下返回不同的值,我希望将这些值粘在一起,所以我仍然得到 2 行数据,如ID_PLANNING_DETAIL = 13683 (在这种情况下,行数取决于ITEM的数量它们是 6 和 7)。

所以返回数据将如下所示:

NO_PO_MYSAP ID_PLANNING_DETAIL ITEM BL
5501        13683              6    2019-11-28
5501        13683              7    2019-11-28
1101        13685              6    2019-12-10, 2019-12-11
1101        13685              7    2019-12-10, 2019-12-11

标签: sqlsql-servermultiple-columns

解决方案


这里这个演示可以帮助 SQLFiddle

SELECT distinct NO_PO_MYSAP, 
                ID_PLANNING_DETAIL,
                ITEM,  
                BL = STUFF((SELECT ', ' + bl_date
               FROM Table_bl bl  -- your table name from bl_date --
               WHERE bl.ID = A.ID
              FOR XML PATH('')), 1, 2, '')
FROM   v_temp_iseecargo_planning A 
       LEFT JOIN tbl_iseecargo_trx_planning_detail B 
              ON A.id_planning = B.id_planning  AND B.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_trx_lifting C 
              ON A.id_planning = C.id_planning AND C.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_trx_lifting_detail D 
              ON C.id_lifting = D.id_lifting AND D.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_md_port E 
              ON B.id_port_loading = E.id_port AND E.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_md_port F 
              ON B.id_port_discharge = F.id_port AND F.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_md_item G 
              ON B.id_item = G.id_item AND G.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_trx_vessel_acceptance H 
              ON C.id_lifting = H.id_lifting AND H.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_md_vessel I 
              ON H.id_vessel = I.id_vessel AND I.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_md_uom J 
              ON B.id_uom = J.id_uom AND J.CHANGEID <> 'D'
       LEFT JOIN tbl_iseecargo_md_shipping_type K 
              ON id_shipping_type_temp = K.id_shipping_type AND K.CHANGEID <> 'D'
       LEFT JOIN (SELECT DISTINCT id_planning_detail, 
                                  no_po_mysap 
                  FROM 
       tbl_iseecargo_trx_procurement_detail
       where CHANGEID <> 'D') L 
              ON b.id_planning_detail = L.id_planning_detail 
WHERE  A.ID_PLANNING in (13683, 13685) and B.id_uom = '3'
order by ALD_AWAL desc;

推荐阅读