从这3个MySQL SELECT查询中进行单个查询的提示?

时间:2013-05-05 00:00:27

标签: mysql select

我有这个MySql表及其数据:

CREATE TABLE IF NOT EXISTS `invoices` (
  `invoice_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `invoice_owner` int(11) NOT NULL,
  `customer_id` int(11) NOT NULL,
  `invoice_no` int(11) NOT NULL,
  `invoice_date` date NOT NULL,
  `invoice_due_date` date NOT NULL,
  `invoice_status` enum('open','cancelled','overdue','closed','archived') NOT NULL,
  `tax1_desc` varchar(50) NOT NULL,
  `tax1_rate` float(6,3) NOT NULL,
  `tax2_desc` varchar(50) NOT NULL,
  `tax2_rate` float(6,3) NOT NULL,
  `invoice_total` float(11,2) NOT NULL DEFAULT '0.00',
  `invoice_notes` text,
  PRIMARY KEY (`invoice_id`),
  KEY `customer_invoice` (`customer_id`,`invoice_no`),
  KEY `invoice_owner` (`invoice_owner`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1005 ;



INSERT INTO `invoices` (`invoice_id`, `invoice_owner`, `customer_id`, `invoice_no`, `invoice_date`, `invoice_due_date`, `invoice_status`, `tax1_desc`, `tax1_rate`, `tax2_desc`, `tax2_rate`, `invoice_total`, `invoice_notes`) VALUES
 (999, 1, 0, 999, '2012-12-13', '2013-01-13', 'archived', '', 0.000, '', 0.000, 255.48, NULL),
(1000, 1, 0, 1000, '2013-04-14', '2013-05-14', 'cancelled', '', 0.000, '', 0.000, 105.28, NULL),
(1001, 1, 0, 1001, '2013-04-13', '2013-05-13', 'closed', '', 0.000, '', 0.000, 202.33, NULL),
(1002, 1, 0, 1002, '2013-04-15', '2013-05-14', 'open', '', 0.000, '', 0.000, 1113.85, NULL),
(1003, 1, 0, 1003, '2013-03-25', '2013-04-25', 'overdue', '', 0.000, '', 0.000, 114.75, NULL),
(1004, 0, 0, 1004, '2013-02-28', '2013-03-28', 'overdue', '', 0.000, '', 0.000, 2890.56, NULL);

我必须做一个能给我3笔钱的选择:

  1. 总逾期发票

    SELECT SUM(invoice_total)AS逾期发票,其中invoice_status ='overdue'

  2. 总共过期1-30天

    SELECT SUM(invoice_total)AS逾期FROM发票,其中invoice_status ='overdue'和invoice_due_date BETWEEN invoice_due_date + 1 AND invoice_due_date + 30

  3. 逾期超过30天

    SELECT SUM(invoice_total)AS逾期FROM发票其中invoice_status ='overdue'AND invoice_due_date> = invoice_due_date + 31

  4. 当然,逾期总数=逾期1-30天+逾期超过30天

    问题:如何在一个SQL查询中完成所有操作?

    我必须返回3个号码:逾期,逾期1-30,逾期超过30

1 个答案:

答案 0 :(得分:1)

使用一些MySQL主义来缩短它,像这样的东西应该这样做;只需在同一行上使用3个单独的总和;

SELECT 
  SUM(invoice_total) AS overdue1, 
  SUM(invoice_total *
    (NOW() BETWEEN invoice_due_date + INTERVAL 1 DAY 
     AND invoice_due_date + INTERVAL 30 DAY)) AS overdue2,
  SUM(invoice_total *
    (NOW() > invoice_due_date + INTERVAL 30 DAY)) AS overdue3
FROM invoices
WHERE invoice_status = 'overdue'

An SQLfiddle to test with