将行显示为服装产品的列

时间:2014-08-29 04:31:46

标签: php mysql sql mysqli mysql-workbench

我在电子商务网站上工作。试图将服装尺寸保持为列 here is my stock table

没有“group by productid”条款的

片段

select d.id,
(case when s.sizeid = 1 then 1 else 0 end) as "S"  ,
(case when s.sizeid = 2 then 1 else 0 end) as "M",
(case when s.sizeid = 3 then 1 else 0 end) as "L"  ,
(case when s.sizeid = 4 then 1 else 0 end) as "XL",
(case when s.sizeid = 5 then 1 else 0 end) as "XXL"  
from datatest d
inner join stock s on d.id = s.productid

result

带有“按产品ID分组”的

结果如下

select d.id,
(case when s.sizeid = 1 then 1 else 0 end) as "S"  ,
(case when s.sizeid = 2 then 1 else 0 end) as "M",
(case when s.sizeid = 3 then 1 else 0 end) as "L"  ,
(case when s.sizeid = 4 then 1 else 0 end) as "XL",
(case when s.sizeid = 5 then 1 else 0 end) as "XXL"  
from datatest d
inner join stock s on d.id = s.productid
group by d.id

result

请帮帮我

1 个答案:

答案 0 :(得分:0)

我想你想要的是尺寸的所有列的总和,共享相同的产品ID。

SUM()功能会在您使用GROUP BY

时为您执行此操作
select d.id,
SUM( (case when s.sizeid = 1 then 1 else 0 end) ) as "S"  ,
SUM( (case when s.sizeid = 2 then 1 else 0 end) ) as "M",
SUM( (case when s.sizeid = 3 then 1 else 0 end) ) as "L"  ,
SUM( (case when s.sizeid = 4 then 1 else 0 end) ) as "XL",
SUM( (case when s.sizeid = 5 then 1 else 0 end) ) as "XXL"  
from datatest d
inner join stock s on d.id = s.productid
group by d.id