在2个表中使用2个总和,同时在另一个表中使用group by

时间:2016-05-26 14:23:19

标签: sql database ms-access

我在数据库上测试此查询时遇到问题。该查询使用5个表:table_1,table_2等。我要做的是从table_1得到一个死亡总和,以及table_5的出生总和。我希望通过table_4中名为AnimalGroup的属性对这些总和进行分组,但是当我这样做时,总和开始加倍。我还想检查哪些金额更高。我加入了桌子。我现在拥有的:

SELECT t4.AnimalGroup, SUM(t1.Amount * t3.DeathRate), SUM(t5.Amount * t3.LiveRate)
FROM Table_1 t1, Table_2 t2, Table_3 t3, Table_4 t4, Table_5 t5
WHERE  t1.t2ID = t2.t2ID
AND t2.t2ID = t3.t2ID
AND t3.t4ID = t4.t4ID
AND t4.t4ID = t5.t4ID
GROUP BY t4.AnimalGroup
HAVING SUM(t1.Amount * t3.DeathRate) > SUM(t5.Amount * t3.LiveRate)

死亡金额从一开始就不会翻倍,但会增加更多记录。现金总额从一开始就翻了一番。我尝试了很多东西,但我找不到解决办法;我想我需要某种子查询,但我不知道在哪里。如果他们停止加倍,我应该得到我需要的东西。我也希望看到两个总和。这是我现在得到的数据:

AnimalGroup|SUMDeath|SUMLive
---------------------------------
Birds      |48.6    |50.7
Cats       |30      |28
Insects    |50      |20
---------------------------------

我想要的是:

AnimalGroup|SUMDeath|SUMLive
---------------------------------
Birds      |24.3    |25.35
Cats       |15      |14
Insects    |25      |10
---------------------------------

Create table table_1 (
t1ID  integer,
t2ID  integer,
Amount  decimal(10, 4),

Constraint pk_t1
   primary key (t1ID),

Constraint fk_t1
primary key ( t2ID)
references table_2(t2ID)
);go

Create table table_2 (
t2ID  integer,

Constraint pk_t2
   primary key (t2ID)
);go

Create table table_3 (
t2ID  integer,
t4ID  integer,
Name  varchar(30),
Deathrate  decimal(10, 4),
Liverate  decimal(10,4),

Constraint pk_t3
   primary key (t2ID, t4ID),
Constraint fk_t3_t2
 foreign key(t2ID)
 references table_2(t2ID),
Constraint fk_t3_t4
foreign key(t4ID)
references table_4(t4ID)
);go

Create table table_4 (
t4ID  integer,
AnimalGroup  varchar(30),

Constraint pk_t4
   primary key (t4ID)
);go

    Create table table_5 (
t5ID  integer,
t4ID  integer,

Constraint pk_t5
primary key(t5ID),

Constraint pk_t5_t4
   foreign key (t4ID)
references table_4(t4ID)
);go

编辑:添加了一些示例数据和创建脚本。查询已更改。

1 个答案:

答案 0 :(得分:1)

这可能接近你想要的......

在派生表中执行group by部分。使用case表达式来选择最高的死亡率和活力:

select AnimalGroup, dr, lr, case when dr > lr then dr else lr end
from
(
    SELECT t4.AnimalGroup as AnimalGroup,
           SUM(t1.Amount * t3.DeathRate) as dr,
           SUM(t5.Amount * t3.LiveRate) as lr
    FROM Table_1 t1, Table_2 t2, Table_3 t3, Table_4 t4, Table_5 t5
    WHERE  t1.t1ID = t2.t2ID
     AND t2.t2ID = t3.t3ID
     AND t3.t3ID = t4.t4ID
     AND t4.t4ID = t5.t5ID
    GROUP BY t4.AnimalGroup
) dt