您好我正在学习SQL,我正在尝试从多个表中检索一些数据而无法让它显示我希望如何,所以我只是想知道这是否可能,如果是这样,有人会建议一种方法,见下文:
Table1: Table2: Table3
Package Licenses Package Licenses Package Licenses
====================== ====================== =====================
Product1 20 Product1 15 Product1 0
Product2 15 Product2 5 Product2 5
Product3 10 Product3 10 Product3 0
我希望Licenses列中的值根据包名称相互添加,如果可能的话显示如下:
Package Licenses
======================
Product1 35
Product2 25
Product3 20
如果有人能让我知道如何做到这一点,如果有可能,请告诉我。
答案 0 :(得分:2)
这是您需要研究的UNION ALL
条款和GROUP BY
声明。
解决方案的要点是
UNION ALL
GROUP BY
和SUM
聚合函数计算子选择结果的总许可证SQL声明
SELECT Package, SUM(Licenses) AS Licenses
FROM (
SELECT Package, Licenses FROM Table1 UNION ALL
SELECT Package, Licenses FROM Table2 UNION ALL
SELECT Package, Licenses FROM Table3
) t
GROUP BY
Package
答案 1 :(得分:1)
试试这个:
SELECT Package, SUM(Licences) as TotalLicences
FROM (
SELECT Package, Licences FROM Table1
UNION ALL
SELECT Package, Licences FROM Table2
UNION ALL
SELECT Package, Licences FROM Table3
) AS AllLicences
GROUP BY Package
答案 2 :(得分:0)
您可以使用union
创建所有许可证的视图,并使用sum
:
select Package
, sum(Licences) as Licences
from (
select Package
, Licences
from Table1
union all
select Package
, Licences
from Table2
union all
select Package
, Licences
from Table3
) as SubQueryAlias
group by
Package