按父ID进行SQL格式化

时间:2017-11-02 03:08:46

标签: sql

我有这样的数据



<associations>
<cart_rows>
        <cart_row>
        <id_product>219</id_product>
        <id_product_attribute/>
        <id_address_delivery/>
        <quantity>1</quantity>
        </cart_row>
<cart_row><id_product>219</id_product><quantity>1</quantity></cart_row><cart_row><id_product>219</id_product><quantity>3</quantity></cart_row></cart_rows>
</associations>
&#13;
&#13;
&#13;

我想得到这样的东西

&#13;
&#13;
| ID | Child_ID | quantity | type |
|----|----------|----------|------|
|  1 |          |       28 | B    |
|  2 |        1 |       14 | S    |
|  3 |        1 |       10 | S    |
|  4 |        2 |       14 | K    |
|  5 |        2 |       10 | K    |
|  6 |        3 |       28 | P    |
|  7 |          |       10 | B    |
|  8 |        7 |        8 | S    |
|  9 |        7 |        2 | S    |
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

很难理解你到底想要做什么。但这看起来像一个枢轴可以用来完成类似的事情。例如:

SELECT *
FROM
(SELECT id, quantity, type
 FROM t) main
PIVOT
(SUM(quantity)
 FOR type in ([B], [K], [P], [S])) piv

返回:

    id  B   K   P   S
1   1   28  NULL    NULL    NULL
2   2   NULL    NULL    NULL    14
3   3   NULL    NULL    NULL    10
4   4   NULL    14  NULL    NULL
5   5   NULL    10  NULL    NULL
6   6   NULL    NULL    28  NULL
7   7   10  NULL    NULL    NULL
8   8   NULL    NULL    NULL    8
9   9   NULL    NULL    NULL    2