如何在列中复制行值?

时间:2016-07-24 11:49:26

标签: sql sql-server sql-server-2012

我有一张这样的表:

07-24 12:20:50.849  16574-16591/com.example.cann W/System.err? org.json.JSONException: Value  at headers of type java.lang.String cannot be converted to JSONArray
07-24 12:20:50.852  16574-16591/com.example.cann W/System.err? at org.json.JSON.typeMismatch(JSON.java:100)
07-24 12:20:50.852  16574-16591/com.example.cann W/System.err? at org.json.JSONObject.getJSONArray(JSONObject.java:588)
07-24 12:20:50.853  16574-16591/com.example.cann W/System.err? at com.example.cann.CategoryActivity$LoadComments.doInBackground(CategoryActivity.java:82)
07-24 12:20:50.853  16574-16591/com.example.cann W/System.err? at com.example.cann.CategoryActivity$LoadComments.doInBackground(CategoryActivity.java:61)

但是我想在这样的新表中显示它:

Service_order     Part_code1  Part_code2       Part_code3     Part_code4        Part_code5

    4182864919    GH82-11218A GH96-09406A      GH81-13594A    GH02-11552A       GH02-11553A
    4182868153    GH97-17670B             
    4182929636    GH97-17260C GH02-10203A         
    4182953067    GH97-17940C             
    4182954688    GH82-10555A GH97-17852A      GH81-13071A     
    4182955036    GH97-17940C             

我尝试加入和联盟,但它没有给我我想要的结果。 该怎么办?

2 个答案:

答案 0 :(得分:2)

在SQL Server中,一种简单的方法是使用APPLY

进行忽略
select t.service_order, v.part_code
from t cross apply
     (values(Part_code1), (Part_code2), (Part_code3), (Part_code4), (Part_code5)
     ) v(part_code)
where v.part_code is not null;

在MySQL或SQL Server中,您可以使用union all

select t.service_order, part_code1 as part_code from t where part_code1 is not null union all
select t.service_order, part_code2 as part_code from t where part_code2 is not null union all
select t.service_order, part_code3 as part_code from t where part_code3 is not null union all
select t.service_order, part_code4 as part_code from t where part_code4 is not null union all
select t.service_order, part_code5 as part_code from t where part_code5 is not null;

答案 1 :(得分:1)

如果服务订单可以包含多个partCodes,则应该有一个带有复合键的表作为规范化的一部分。 在这种情况下,service_order和partCodes将是每行的唯一键。

使用这样的模式,只需SELECT * FROM [table_name],假设您有一个SQL数据库。

相关问题