我不确定这在一个 mysql 查询中是否可行,所以我可能只是通过 php 合并结果。
我有 2 个表:'users' 和 'billing'
我正在尝试对这两个表中可用的每个日期的汇总事件进行分组。 “用户”不是历史数据,但“账单”包含每笔交易的记录。
在这个例子中,我显示了一个用户的状态,我想根据创建日期和存款金额求和,我也想根据创建日期求和。我意识到数据之间有点脱节,但我想将所有数据放在一起并显示如下所示。这将按创建时间显示所有用户的概览,以及总交易旁边的当前状态。
我已经尝试过 UNION 和 LEFT JOIN,但我似乎都无法正常工作。
并集示例非常接近,但没有将日期组合成一行。
(
SELECT
created,
SUM(status) as totalActive,
NULL as totalDeposit
FROM users
GROUP BY created
)
UNION
(
SELECT
created,
NULL as totalActive,
SUM(transactionAmount) as totalDeposit
FROM billing
GROUP BY created
)
我也尝试过使用日期查找表并加入日期,但 SUM 值被多次添加。
注意:我根本不关心 userIds,但这里有它作为示例。
用户表 (其中“1”的状态表示“事件”) (每个用户一条记录)
created | userId | status
2010-03-01 | 10 | 0
2010-03-01 | 11 | 1
2010-03-01 | 12 | 1
2010-03-10 | 13 | 0
2010-03-12 | 14 | 1
2010-03-12 | 15 | 1
2010-03-13 | 16 | 0
2010-03-15 | 17 | 1
帐单表 (为每个计费“交易”实例创建的记录
created | userId | transactionAmount
2010-03-01 | 10 | 50
2010-03-01 | 18 | 50
2010-03-01 | 19 | 100
2010-03-10 | 89 | 55
2010-03-15 | 16 | 50
2010-03-15 | 12 | 90
2010-03-22 | 99 | 150
期望的结果:
created | sumStatusActive | sumStatusInactive | sumTransactions
2010-03-01 | 2 | 1 | 200
2010-03-10 | 0 | 1 | 55
2010-03-12 | 2 | 0 | 0
2010-03-13 | 0 | 0 | 0
2010-03-15 | 1 | 0 | 140
2010-03-22 | 0 | 0 | 150
表转储:
CREATE TABLE IF NOT EXISTS `users` (
`created` date NOT NULL,
`userId` int(11) NOT NULL,
`status` smallint(6) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `users` (`created`, `userId`, `status`) VALUES
('2010-03-01', 10, 0),
('2010-03-01', 11, 1),
('2010-03-01', 12, 1),
('2010-03-10', 13, 0),
('2010-03-12', 14, 1),
('2010-03-12', 15, 1),
('2010-03-13', 16, 0),
('2010-03-15', 17, 1);
CREATE TABLE IF NOT EXISTS `billing` (
`created` date NOT NULL,
`userId` int(11) NOT NULL,
`transactionAmount` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `billing` (`created`, `userId`, `transactionAmount`) VALUES
('2010-03-01', 10, 50),
('2010-03-01', 18, 50),
('2010-03-01', 19, 100),
('2010-03-10', 89, 55),
('2010-03-15', 16, 50),
('2010-03-15', 12, 90),
('2010-03-22', 99, 150);
最佳答案
试试这个:
Select created, sum(status) as totalActive, sum(transactionAmount) as totalDeposit
From
( (
SELECT
created,
status,
0 as transactionAmount
FROM users
)
UNION
(
SELECT
created,
0 as status,
transactionAmount
FROM billing
) ) as x group by created
关于mysql - 跨 2 个表的 GROUP BY 和 SUM 不同日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2480758/