【发布时间】:2010-03-19 21:42:14
【问题描述】:
我不确定这是否可以在一个 mysql 查询中实现,所以我可能只是通过 php 组合结果。
我有 2 个表:'users' 和 'billing'
我正在尝试对这两个表中可用的每个日期的总活动进行分组。 '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);
【问题讨论】:
标签: mysql