MySQL:将没有列的列分组为null
我试图将这个“虚构”表分组(几个连接和if的结果) 表,它是怎样的:MySQL:将没有列的列分组为null,mysql,sql,Mysql,Sql,我试图将这个“虚构”表分组(几个连接和if的结果) 表,它是怎样的: ProductID PriceForOneYear PriceForTwoYears PriceForThreeYears PriceForFourYears PriceForFiveYears 1 1.00 NULL NULL NULL NULL 1 NULL 1.50
ProductID PriceForOneYear PriceForTwoYears PriceForThreeYears PriceForFourYears PriceForFiveYears
1 1.00 NULL NULL NULL NULL
1 NULL 1.50 NULL NULL NULL
1 NULL NULL 2.00 NULL NULL
1 NULL NULL NULL 2.50 NULL
1 NULL NULL NULL NULL 3.00
2 5.00 NULL NULL NULL NULL
2 NULL 5.50 NULL NULL NULL
2 NULL NULL 6.00 NULL NULL
2 NULL NULL NULL 6.50 NULL
2 NULL NULL NULL NULL 7.00
表,它应该是什么:
ProductID PriceForOneYear PriceForTwoYears PriceForThreeYears PriceForFourYears PriceForFiveYears
1 1.00 1.50 2.00 2.50 3.00
2 5.00 5.50 6.00 6.50 7.00
空值应该掉出来
有什么想法吗
到目前为止,我尝试了“分组方式”和“分组方式”(不同的)
创建“虚拟表”的查询:
将查询更改为聚合查询,并在列上使用
max()
:
SELECT `tblproducts`.`id` AS `productid`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '1', `tblpricing`.`monthly`, NULL)) AS `priceforoneyear`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '2', ROUND(`tblpricing`.`monthly` / 2, 2), NULL)) AS `pricefortwoyears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '3', ROUND(`tblpricing`.`monthly` / 3, 2), NULL)) AS `priceforthreeyears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '4', ROUND(`tblpricing`.`monthly` / 4, 2), NULL)) AS `priceforfouryears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '5', ROUND(`tblpricing`.`monthly` / 5, 2), NULL)) AS `priceforfiveyears`
FROM `tblproducts` INNER JOIN
`tblproductconfigoptionssub`
ON `tblproducts`.`id` = `tblproductconfigoptionssub`.`configid` INNER JOIN
`tblpricing`
ON `tblproductconfigoptionssub`.`id` = `tblpricing`.`relid`
WHERE `tblproducts`.`gid` = '1' AND `tblpricing`.`type` = 'configoptions'
GROUP BY `tblproducts`.`id`;
SELECT `tblproducts`.`id` AS `productid`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '1', `tblpricing`.`monthly`, NULL)) AS `priceforoneyear`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '2', ROUND(`tblpricing`.`monthly` / 2, 2), NULL)) AS `pricefortwoyears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '3', ROUND(`tblpricing`.`monthly` / 3, 2), NULL)) AS `priceforthreeyears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '4', ROUND(`tblpricing`.`monthly` / 4, 2), NULL)) AS `priceforfouryears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '5', ROUND(`tblpricing`.`monthly` / 5, 2), NULL)) AS `priceforfiveyears`
FROM `tblproducts` INNER JOIN
`tblproductconfigoptionssub`
ON `tblproducts`.`id` = `tblproductconfigoptionssub`.`configid` INNER JOIN
`tblpricing`
ON `tblproductconfigoptionssub`.`id` = `tblpricing`.`relid`
WHERE `tblproducts`.`gid` = '1' AND `tblpricing`.`type` = 'configoptions'
GROUP BY `tblproducts`.`id`;