简体   繁体   中英

MySQL - Reorganizing One Column/Three Rows into Three Columns/One Row?

I'm completely new to mySQL and am struggling with the below task. I have a table, t1, which lists three columns:

ITEM    SIZE    COUNT
------------------------
1001    small   11
1001    medium  6
1001    large   34
1002    small   10
1002    large   23
1003    small   81
1003    medium  12
1003    large   38  
...etc...

This data goes on for hundreds of tuples. What I ultimately need to do is reorganize the count like this:

ITEM   SMALL   MEDIUM   LARGE
-----------------------------
1001   11      6        34
1002   10      0        23
1003   81      12       38

...etc...

Note that Item 1002, Medium size doesn't appear in the first table; hence its value is 0 in the second table.

Any suggestions? Pointers? I assume the solution is something like this:

SELECT item 'ITEM', if(ITEM=1001 and SIZE=???, SIZE) 'SMALL', ...etc...
FROM t1;

But that's as far as I got.

Rextester example: http://rextester.com/VRVPKM75531

Pivot or conditional aggregation (mysql doesn't support pivot)

SELECT item 'ITEM'
     , coalesce(max(case when size = 'small' then count end),0) as SMALL
     , coalesce(max(case when size = 'medium' then count end),0) as MEDIUM
     , coalesce(max(case when size = 'large' then count end),0) as LARGE
FROM t1
GROUP BY ITEM

If you have multiple counts per item size and you need to "SUM" them you could do that instead of max. Max in this case implies 1 record per item and size; or you'll lose data.

One can use coalesce when no such record exists to substitute a 0 as needed. Or not use coalesce and allow the value to be NULL.

my answer is (for all intents and purposes) the same as @xQbert but using "create table as select" to put the values directly into a new table.

CREATE TABLE t2 AS
  SELECT
    ITEM,
    SUM(CASE WHEN SIZE = "small" THEN `COUNT` ELSE 0 END) AS "SMALL",
    SUM(CASE WHEN SIZE = "medium" THEN `COUNT` ELSE 0 END) AS "MEDIUM",
    SUM(CASE WHEN SIZE = "large" THEN `COUNT` ELSE 0 END) AS "LARGE"
  FROM t1
  GROUP BY ITEM;

I use backticks around count as its a mySQL keyword and while not required I habitually backtick any thing that looks like a keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM