如何对两个表进行分组并应用聚合函数?

时间:2019-04-12 02:48:48

标签: mysql sql database oracle

模式:(original res

enter image description here

如何在将两个表同时分组的同时在两个表上应用聚合函数? 我需要血型表和捐赠者不满意时需要订购的数量。 在上述模式中,查询应返回A + 14,因为受体要求是15,而捐助者仅提供1。所有其他血型都满足。 请提出一种方法。预先感谢!

2 个答案:

答案 0 :(得分:0)

您可以使用

SELECT bg, SUM(total)
FROM
(
    (SELECT bg, SUM(amount) AS total FROM Donor GROUP BY bg) UNION
    (SELECT bg, -SUM(amount) AS total FROM Acceptor GROUP BY bg)
) a
GROUP BY bg
HAVING SUM(total) < 0;

这会使您(A +,-14)表示A +组不足14。

这是通过首先对供体中的可用血型求和,然后对接受器中的可用血型求和,然后再将它们全部加起来来实现的。

您可以通过删除HAVING子句来获得所有结果,或者您可以通过SELECT使用-SUM(total)而不是SUM(total)来获得最初请求的结果。< / p>

答案 1 :(得分:0)

在BG列上进行简单的联接,并带有by的组将显示您正在寻找的结果

创建示例表

create table `donor` (
    `did` int(10) ,
    `name` varchar(30),
    `gender` varchar(1),
    `city` varchar(30),
    `bg` varchar(4),
    `amount` int(10)
);
create table `acceptor` (
    `did` int(10),
    `name` varchar(30),
    `gender` varchar(1),
    `city` varchar(30),
    `bg` varchar(4),
    `amount` int(10)
);

添加示例数据

insert into `donor`
(`name`,`gender`,`city`,`bg`,`amount`)
VALUES
('MARIA','F','Warne,NH','AB+',7),
('RUBY','F','East Natchitoche, PA','AB+',3),
('CHARLES','M','East Natchitoche, PA','A-',6),
('DOROTHY','F','East Natchitoche, PA','AB+',9),
('MICHAEL','M','Warne,NH','A+',1);

insert into `acceptor`
(`name`,`gender`,`city`,`bg`,`amount`)
VALUES
('LINDA','F','Warne,NH','A+',9),
('CHARLES','M','Warne,NH','AB+',8),
('RICHARD','M','East Natchitoche, PA','AB+',3),
('LINDA','F','East Natchitoche, PA','A+',1),
('PATRICIA','F','Warne,NH','A+',5);

示例查询:

select 
    a.`bg`,
    sum(a.`amount`) as `num donor units`,
    sum(b.`amount`) as `num acceptor units`
from `donor` a
join `acceptor` b
    on a.`bg` = b.`bg`
GROUP BY a.`bg`;

结果

| bg  | num donor units | num acceptor units |
| --- | --------------- | ------------------ |
| A+  | 3               | 15                 |
| AB+ | 38              | 33                 |

另一个生成订单报告的查询:

select 
    a.`bg`,
    sum(a.`amount`) as `num donor units`,
    sum(b.`amount`) as `num acceptor units`,
    if(sum(a.`amount`) < sum(b.`amount`),
        CONCAT('Order ',sum(b.`amount`) - sum(a.`amount`),' Units'),
        'None Needed') as 'Ordering'
from `donor` a
join `acceptor` b
    on a.`bg` = b.`bg`
GROUP BY a.`bg`;

结果

| bg  | num donor units | num acceptor units | Ordering       |
| --- | --------------- | ------------------ | -------------- |
| A+  | 3               | 15                 | Order 12 Units |
| AB+ | 38              | 33                 | None Needed    |