【问题标题】:Tips to make one single query from these 3 MySQL SELECT queries?从这 3 个 MySQL SELECT 查询中进行一个查询的提示?
【发布时间】:2025-12-06 11:30:01
【问题描述】:

我有这个 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 overded FROM invoices where invoice_status = 'overdue'

  2. 得到总逾期 1-30 天

    在 invoice_status = 'overdue' AND invoice_due_date BETWEEN invoice_due_date+1 AND invoice_due_date+30 的发票中选择 SUM (invoice_total) 作为逾期的发票

  3. 总逾期超过 30 天

    SELECT SUM (invoice_total) AS overded from invoices where invoice_status = 'overdue' AND invoice_due_date >= invoice_due_date+31

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

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

我要返回3个数字:总逾期、逾期1-30、逾期超过30

【问题讨论】:

  • 提出问题的好方法 点赞

标签: mysql select


【解决方案1】:

使用一些 MySQLisms 让它更短一点,这样的事情应该可以做到;只需在同一行上使用 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.

【讨论】:

  • 非常感谢!我认为这将完成这项工作。感谢 SQLfiddle。我不知道它存在。