加入两个表格

时间:2014-08-15 07:24:42

标签: mysql sql join where

我有两张桌子:' Project'和'项目月刊'。

| PROJECT_ID |  TITLE |    | ID | PROJECT_ID |  MONTH | EXPENSE |
-----------------------    --------------------------------------
|          1 | title1 |    |  1 |          1 |      1 |     100 |
|          2 | title2 |    |  2 |          1 |      2 |    2000 |
|          3 | title3 |    |  3 |          1 |      3 |     900 |
                           |  4 |          1 |      4 |     900 | 
                           |  5 |          2 |      1 |     200 |
                           |  6 |          2 |      2 |     200 |
                           |  7 |          3 |      1 |     500 | 

我想要一张这样的表:

| PROJECT_ID |  TITLE | MONTH_1 | MONTH_2 | MONTH_3 | MONTH_4 |
---------------------------------------------------------------
|          1 | title1 |     100 |    2000 |     900 |     900 |
|          2 | title2 |     200 |     200 |     NULL|     NULL|
|          3 | title3 |     500 |    NULL |     NULL|     NULL|

我是否只能通过JOIN和没有子查询来实现它?

谢谢!

3 个答案:

答案 0 :(得分:3)

将行转换为列称为旋转。一种方法是group by每个项目。该小组将成为一个单一的行。在组内,您每月定义一列。该列总结了一个特定月份的费用:

select  p.PROJECT_ID
,       p.TITLE
,       sum(case when m.month = 1 then m.expense end) as MONTH_1
,       sum(case when m.month = 2 then m.expense end) as MONTH_2
...
from    project p
join    monthly m 
on      p.PROJECT_ID = m.PROJECT_ID
group by 
        p.PROJECT_ID
,       p.TITLE

答案 1 :(得分:2)

试试这个

select p.PROJECT_ID,p.TITLE,
case when month=1 then EXPENSE end as Month_1,
case when month=2 then EXPENSE end as Month_2,
case when month=3 then EXPENSE end as Month_3,
case when month=4 then EXPENSE end as Month_4
from Project p inner join ProjectMonthly' pm on p.PROJECT_ID=pm.PROJECT_ID

答案 2 :(得分:2)

您可以通过使用带有max的案例来获得所需的结果集,下面的查询只会给出4个月的结果,如果您有超过4个月的话,那么您必须为所有月份编写案例并选择最大值在一个月的值中有更大的价值,我已经使用了内部联接,因此如果任何项目没有月度数据并且您仍然希望它将结果更改内部联接返回到左联接,则将返回ProjectMonthly中仅存在这些项目的项目

SELECT p.PROJECT_ID,p.TITLE,
MAX(CASE WHEN MONTH=1 THEN EXPENSE END) AS Month_1,
MAX(CASE WHEN MONTH=2 THEN EXPENSE END) AS Month_2,
MAX(CASE WHEN MONTH=3 THEN EXPENSE END) AS Month_3,
MAX(CASE WHEN MONTH=4 THEN EXPENSE END) AS Month_4
FROM Project p 
INNER JOIN ProjectMonthly pm 
ON p.PROJECT_ID=pm.PROJECT_ID
GROUP BY p.PROJECT_ID

Fiddle Demo