结合查询.. PIVOT不起作用

时间:2017-06-21 00:19:17

标签: php mysql sql

我的查询有问题。我现在有2个查询,工作正常。但是当我想用PIVOT添加另一个查询时,它不起作用。我尝试了很多东西,但没有任何作用。

这是我的前两个查询



$query = "SET SQL_BIG_SELECTS = 1;";
$query .= "SELECT * FROM datakram, datakram2, datakram3 WHERE datakram.NAME = datakram2.NAME AND datakram2.NAME = datakram3.NAME"




我想为表添加一个PIVOT" datakram4"。但我只想要NAME等于其他表中NAME的行。如果没有PIVOT它可以工作..

我的PIVOT代码。



SELECT  `name` ,
 MAX( CASE WHEN  `year` =2017 THEN  `income` ELSE 0 END ) AS INCOME_2017,
 MAX( CASE WHEN  `year` =2017 THEN  `expense` ELSE 0 END ) AS EXPENSE_2017,
 MAX( CASE WHEN  `year` =2016 THEN  `income` ELSE 0 END ) AS INCOME_2016,
 MAX( CASE WHEN  `year` =2016  THEN  `expense` ELSE 0 END ) AS EXPENSE_2016
 FROM  `test_data` GROUP BY  `name` 




我在我的php脚本中使用multi_query。

2 个答案:

答案 0 :(得分:2)

只需加入查询:

SELECT d4.* 
FROM datakram d1
INNER JOIN datakram2 d2
  ON d1.`NAME` = d2.`NAME`
INNER JOIN datakram3 d3 
  ON d2.`NAME` = d3.`NAME`
INNER JOIN
   (SELECT `name` ,
      MAX(CASE WHEN `year`=2017 THEN `income` ELSE 0 END) AS INCOME_2017,
      MAX(CASE WHEN `year`=2017 THEN `expense` ELSE 0 END) AS EXPENSE_2017,
      MAX(CASE WHEN `year`=2016 THEN `income` ELSE 0 END) AS INCOME_2016,
      MAX(CASE WHEN `year`=2016 THEN `expense` ELSE 0 END) AS EXPENSE_2016
    FROM `test_data` 
    GROUP BY `name`
   ) d4
  ON d3.`NAME` = d4.`name`

答案 1 :(得分:1)

一种简单的方法是过滤WHERE子句:

SELECT  `name` ,
         MAX(CASE WHEN `year` = 2017 THEN `income` ELSE 0 END) AS INCOME_2017,
         MAX(CASE WHEN `year` = 2017 THEN `expense` ELSE 0 END) AS EXPENSE_2017,
         MAX(CASE WHEN `year` = 2016 THEN `income` ELSE 0 END) AS INCOME_2016,
         MAX(CASE WHEN `year` = 2016  THEN `expense` ELSE 0 END) AS EXPENSE_2016
FROM `test_data` td
WHERE EXISTS (SELECT 1 FROM FROM datakram d WHERE d.name = td.NAME) AND
      EXISTS (SELECT 1 FROM FROM datakram2 d WHERE d.name = td.NAME) AND
      EXISTS (SELECT 1 FROM FROM datakram3 d WHERE d.name = td.NAME) 
GROUP BY `name` ;