代码之家  ›  专栏  ›  技术社区  ›  Kasun

如何将数据集设置为行

  •  0
  • Kasun  · 技术社区  · 6 年前

    我的表有下面的记录,我需要的是将下面的结果设置为数据表。

    date        code      lc_code      qty
    7/1/2018    MC20651    1126         322.00
    7/1/2018    MC10102    3356         30.00
    7/1/2018    MC10201    4422         56.00
    7/1/2018    MC10303    5065         55.00
    7/1/2018    MC20902    7012         65.00
    7/1/2018    MC50201    1258         45.00
    7/1/2018    MC10201    1126         86.00
    7/1/2018    MC50201    7012         14.25
    7/1/2018    MC20651    1258         322.00
    7/1/2018    MC20651    3356         78.00
    

    下面是我需要设置为DataTable的内容。你能提供最好的查询吗?


    |  Code     |   1126 |   3356 |   4422 |   5065  |   7012 |   1258 |
    --------------------------------------------------------------------
    |  MC20651  |  322.00|   78.00|   0.00 |   0.00  |   0.00 | 322.00 |
    --------------------------------------------------------------------
    |  MC10102  |   0.00 |  30.00 |   0.00 |   0.00  |   0.00 |   0.00 |
    --------------------------------------------------------------------
    |  MC10201  |   86.00|   0.00 |  56.00 |   0.00  |   0.00 | 134.25 |
    --------------------------------------------------------------------
    |  MC10303  |   0.00 |   0.00 |   0.00 |  55.00  |   0.00 |   0.00 |
    --------------------------------------------------------------------
    |  MC20902  |   0.00 |   0.00 |   0.00 | 960.00  |  65.00 |   0.00 |
    --------------------------------------------------------------------
    |  MC50201  |   0.00 |   0.00 |   0.00 |   0.00  |  14.25 |   45.00|
    --------------------------------------------------------------------
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Michał Turczyn    6 年前

    max(case when ... end) code

    create table tbl(date date, code  char(10), lc_code int, qty float);
    insert into tbl (code,lc_code,qty) values
    ('MC20651', 1126, 322.00),
    ('MC10102', 3356, 30.00),
    ('MC10201', 4422, 56.00),
    ('MC10303', 5065, 55.00),
    ('MC20902', 7012, 65.00),
    ('MC50201', 1258, 45.00),
    ('MC10201', 1126, 86.00),
    ('MC50201', 7012, 14.25),
    ('MC20651', 1258 , 322.00),
    ('MC20651', 3356, 78.00);
    

    select  `code`
            `1126`,
            `3356`,
            `4422`, 
            `5065`,
            `7012`,
            `1258`,
            `1126` + `3356` + `4422` + `5065` + `7012` + `1258` `sum`
    from (
        select `code`,
               max(case lc_code when 1126 then qty else 0 end) `1126`,
               max(case lc_code when 3356 then qty else 0 end) `3356`,
               max(case lc_code when 4422 then qty else 0 end) `4422`,
               max(case lc_code when 5065 then qty else 0 end) `5065`,
               max(case lc_code when 7012 then qty else 0 end) `7012`,
               max(case lc_code when 1258 then qty else 0 end) `1258`
        from tbl
        group by `code`
    ) `a`;