将具有相同ID但不同数据的多行合并为一行

时间:2018-04-17 04:19:00

标签: sql sql-server

如何将具有相同ID但不同数据的多行合并为一行。

我有桌子:

ORDER_ID  MATERIAL  PLAN_QTY    STATUS
3         A         13          OPEN
3         B         13          OPEN
3         C         13          OPEN
3         D         13          CLOSE
3         E         13          OPEN
3         F         13          OPEN
3         G         13          OPEN
4         A         1000        OPEN
4         B         1000        OPEN
4         C         1000        OPEN
4         D         1000        OPEN
4         E         1000        OPEN
4         F         1000        OPEN
4         G         1000        OPEN
5         A         500         CLOSE
5         B         500         CLOSE
5         C         500         CLOSE
5         D         500         CLOSE
5         E         500         CLOSE
5         F         500         CLOSE
5         G         500         CLOSE

我想得到这样的表:

ORDER_ID    PLAN_QTY    STATUS
3           13          IN-PROGRESS
4           1000        OPEN
5           500         CLOSE

2 个答案:

答案 0 :(得分:0)

group by子句与条件聚合

一起使用
select ORDER_ID, PLAN_QTY,
       (case when count(distinct STATUS) > 1 then 'IN-PROGRESS' else             
       (select top 1 STATUS from table where ORDER_ID = t.ORDER_ID) end) as STATUS 
from table t
group by ORDER_ID, PLAN_QTY;    

以其他方式仅使用聚合函数

select ORDER_ID, PLAN_QTY,
       (case when max(STATUS) <> min(STATUS) 
             then 'IN-PROGRESS' else max(STATUS) end) as STATUS 
from table t
group by ORDER_ID, PLAN_QTY;    

答案 1 :(得分:0)

试试这个:

SELECT ORDER_ID, PLAN_QTY, 
CASE WHEN MAX([STATUS]) = MIN([STATUS]) THEN MAX([STATUS]) ELSE 'IN-PROGRESS' END [Status])
FROM tbl
GROUP BY 
ORDER_ID, PLAN_QTY;