简体   繁体   中英

Mysql inner join or left join

I have 1 table products and I would like to extract price of products with type A and B. I try to use INNER JOIN but it returns duplicate record. How can I do this?

 id   |   Price    |     Date    |   Type   |   Size  |
-------------------------------------------------------
 1    |   1,00     |  01/11/2010 |     A    |   7,00  |
 2    |   2,50     |  02/11/2010 |     A    |   8,00  |
 3    |   2,50     |  03/11/2010 |     A    |   9,00  |
 4    |   3,00     |  02/11/2010 |     A    |  10,00  |
 5    |   4,00     |  03/11/2010 |     A    |  11,00  |
 6    |   4,00     |  03/11/2010 |     A    |  12,00  |
 7    |   5,00     |  03/11/2010 |     A    |  13,00  |
 8    |   5,00     |  03/11/2010 |     A    |  14,00  |
 9    |   6,00     |  03/11/2010 |     A    |  15,00  |
10    |   7,00     |  03/11/2010 |     A    |  16,00  |
11    |   1,00     |  03/11/2010 |     B    |  17,00  |
12    |   2,50     |  03/11/2010 |     B    |  18,00  |
13    |   3,00     |  03/11/2010 |     B    |  19,00  |
14    |   3,00     |  03/11/2010 |     B    |  20,00  |
15    |   5,00     |  03/11/2010 |     B    |  21,00  |
16    |   6,00     |  03/11/2010 |     B    |  22,00  |
17    |   7,00     |  03/11/2010 |     B    |  23,00  |
18    |   7,00     |  03/11/2010 |     B    |  24,00  |

And I would like to build a table like this:

 Price    |     Date    |   Size A |   Size B  |
-------------------------------------------------------
 1,00     |  01/11/2010 |    7,00  |   17,00   |
 2,50     |  02/11/2010 |    8,00  |           |
 2,50     |  03/11/2010 |    9,00  |   18,00   |
 3,00     |  02/11/2010 |   10,00  |   19,00   |
 4,00     |  03/11/2010 |   11,00  |           |
 4,00     |  04/11/2010 |   12,00  |           |
 5,00     |  03/11/2010 |   13,00  |   21,00   |
 5,00     |  04/11/2010 |   14,00  |           |
 6,00     |  05/11/2010 |   15,00  |           |
 7,00     |  06/11/2010 |   16,00  |   23,00   |

How can I do that in one query?

Thanks for any help.

select price, 
       date, 
       sum(case when `type` = 'A' then size else 0 end) as SizeA,
       sum(case when `type` = 'B' then size else 0 end) as SizeB
from products
group by price, date
order by price, date

Group by the date to get the data for each date. To get the other columns you need to use aggregate functions like sum() .

If you really need the null values you can do:

case when sum(`type` = 'A') = 0 
     then null 
     else sum(case when `type` = 'A' then size end)
end

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