将列转换为单独的表,列名为值

时间:2017-07-19 09:37:13

标签: sql ms-access

我正在进行提取,我遇到了一个我无法解决的问题。

我的提取看起来像这样:

    <TextView
                                android:id="@+id/tv_toolbar_prod_price"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"

                                android:paddingRight="3dp"
                                android:text="1,290 B"      

android:background="@drawable/strikethru_line"
                                android:textColor="#070707"
                                android:textSize="13sp" />

产品显示为列。所以它不是很容易使用。

我想将我的表与产品分开作为外部表格,如:

+--------+-------+----------+----------+-----+------------+
| ID     | Info1 | Product1 | Product2 | ... | Product300 |
+--------+-------+----------+----------+-----+------------+
| 1      | Paul  | 2        |          |     |            |
+--------+-------+----------+----------+-----+------------+
| 2      | Steve |          | 1        |     |            |
+--------+-------+----------+----------+-----+------------+
| 3      | Mark  | 2        |          |     |            |
+--------+-------+----------+----------+-----+------------+
| ...    |       |          |          |     |            |
+--------+-------+----------+----------+-----+------------+
| 150000 | Felix | 1        |          |     | 2          |
+--------+-------+----------+----------+-----+------------+

最初这个提取是在Excel中,但我为此目的转移到Access。

我对SQL有基本的了解,但还不足以找到解决方案。

2 个答案:

答案 0 :(得分:1)

正如jarlh所写,唯一的SQL解决方案就是:

INSERT INTO TargetTable (ID, Product, Value)

SELECT ID, 'Product1' AS Product, Product1 AS Value FROM SrcTable WHERE Product1 IS NOT NULL
UNION ALL
SELECT ID, 'Product2' AS Product, Product2 AS Value FROM SrcTable WHERE Product2 IS NOT NULL
UNION ALL
etc.

也许将它分成几块,我不确定300 UNION ALL在一次查询中的效果如何。

答案 1 :(得分:0)

你需要打开你的桌子:

https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

SELECT ID, Product, Value
FROM 
   (SELECT ID, Product1, Product2, Product3, Product4, Product5
   FROM products) p
UNPIVOT
   (Value FOR Product IN 
      (Product1, Product2, Product3, Product4, Product5)
)AS unpvt;
相关问题