我想拥有两个不同表的各个列的总和,并将其显示在客户ID匹配的单个查询结果中?

时间:2015-09-28 13:29:33

标签: mysql

Create or replace view cnPointsDetailsvw
as select  sum(cd.value), sum(cd1.points)
from customerdetails cd left join
customerdetails1 cd1 on cd.customerid = cd1.customerid;

问题是以上查询多次为sum

计算column cd1.points

2 个答案:

答案 0 :(得分:1)

在子查询中进行计算,然后加入他们的结果:

SELECT
 CD.sum_value, CD1.sum_points
FROM
 (SELECT sum(value) as sum_value FROM customerdetails) CD
 INNER JOIN (SELECT sum(points) AS sum_points FROM customerdetails1) CD1
   ON 1 = 1

请注意,如果没有匹配的行,则SUM()会返回NULL,因此子查询将返回恰好一条记录 - >任何ON condition都可以,但结果为真。

如果您想按客户分组,请在子查询中进行分组:

SELECT
 CD.customerid, CD.sum_value, CD1.sum_points
FROM
 (
   SELECT customerid, sum(value) as sum_value
   FROM customerdetails
   GROUP BY customerid
 ) CD
 LEFT JOIN
 (
   SELECT customerid, sum(points) AS sum_points
   FROM customerdetails1
   GROUP BY customerid
 ) CD1
   ON CD.customerid = CD1.customerid

<强>更新

要创建视图(并绕过MySQL的限制),您必须创建3个视图:2个子视图,1个加入其结果:

CREATE VIEW customer_value AS 
SELECT SUM(value) as sum_value FROM customerdetails;

CREATE VIEW customer_points AS
SELECT SUM(points) as sum_points FROM customerdetails1;

CREATE VIEW cnPointsDetailsvw AS
SELECT cv.sum_value, cp.sum_points
FROM customer_value cv
INNER JOIN customer_points cp
  ON 1=1;

答案 1 :(得分:1)

如果表customerdetails1只有1行,那么为什么要使用SUM()函数?
只需使用MAX()
我对你的表感到困惑,所以让我给出一个示例结构和数据。

表1

id   points
-----------
1    10
2    20
3    40

table2

id   points
-----------
1    10
1     2
1     4
2    20
3    40
3     5

您的查询应如下所示:

CREATE OR REPLACE VIEW view_name AS 
SELECT t1.id,max(t1.points) as points1, sum(t2.points) as points2
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
GROUP BY t1.id

您的观点应如下所示:

id  points1   points2
---------------------
1      10      16
2      20      20
3      30      45