每行的SUM和过滤结果SUM()IN $ x

时间:2013-12-15 19:16:50

标签: mysql sql database postgresql

MySQL中的数据表:

id  user_id sell_amount sell_currency_id    buy_amount  buy_currency_id type    status  date_add
5   2   2.00000000  1   4.00000000  0   0   0   2013-12-15 19:06:40
6   3   2.60000000  1   5.10000000  0   0   0   2013-12-15 19:06:54 
4   1   1.00000000  1   0.80000000  0   0   0   2013-12-15 19:07:05
7   4   4.00000000  1   8.20000000  0   0   0   2013-12-15 19:07:21
8   5   3.00000000  1   6.00000000  0   1   0   2013-12-15 19:07:40

我必须从此表中选择iduser_idsell_amountsell_currency_id status=0type=0以及SUM }到当前行IN $ x,按ORDER BY buy_amount/sell_amount ASC排序,date_add ASC

$x = 6

的结果
id  user_id sell_amount sell_currency_id    SUM(sell_amount)
4   1   1.00000000  1   1.00000000
6   3   2.60000000  1   3.60000000
5   2   2.00000000  1   5.60000000
7   4   4.00000000  1   9.60000000

我使用MySQL,但如果在这个SQL引擎中做得太复杂,那么我可以更改它,但它应该是最新的解决方案。

表格来源:

CREATE TABLE IF NOT EXISTS `market` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `sell_amount` decimal(19,8) NOT NULL,
  `sell_currency_id` tinyint(3) unsigned NOT NULL,
  `buy_amount` decimal(19,8) unsigned NOT NULL,
  `buy_currency_id` tinyint(3) unsigned NOT NULL,
  `type` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `status` tinyint(3) unsigned NOT NULL,
  `date_change` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `date_add` datetime NOT NULL,
  `date_close` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_market_user1_idx` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;

DATA:

INSERT INTO `market` (`id`, `user_id`, `sell_amount`, `sell_currency_id`, `buy_amount`, `buy_currency_id`, `type`, `status`, `date_change`, `date_add`, `date_close`) VALUES
(4, 1, 1.00000000, 1, 0.80000000, 0, 0, 0, '2013-12-15 19:07:05', '2013-12-12 18:30:04', '2013-12-12 18:30:04'),
(5, 2, 2.00000000, 1, 4.00000000, 0, 0, 0, '2013-12-15 19:06:40', '2013-12-12 18:30:04', '2013-12-12 18:30:04'),
(6, 3, 2.60000000, 1, 5.10000000, 0, 0, 0, '2013-12-15 19:06:54', '2013-12-12 18:30:04', '2013-12-12 18:30:04'),
(7, 4, 4.00000000, 1, 8.20000000, 0, 0, 0, '2013-12-15 19:07:21', '2013-12-12 18:30:04', '2013-12-12 18:30:04'),
(8, 5, 6.00000000, 1, 12.00000000, 0, 1, 0, '2013-12-15 19:07:40', '2013-12-12 18:30:04', '2013-12-12 18:30:04');

编辑: 因为MySQL不适合这个,我将使用PostgreSQL。

0 个答案:

没有答案