选择日期范围介于或更大

时间:2017-12-02 12:00:16

标签: mysql

数据

CREATE TABLE `employees_salaries` (
  `PK_salary` bigint(20) NOT NULL,
  `PK_worker` bigint(20) NOT NULL,
  `contract_start` date NOT NULL,
  `contract_end` date NOT NULL,
  `gross` decimal(10,2) NOT NULL,
  `insurence_cost1` decimal(10,2) NOT NULL,
  `insurence_cost2` decimal(10,2) NOT NULL,
  `to_payout` decimal(10,2) NOT NULL,
  `due` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `employees_salaries` (`PK_salary`, `PK_worker`, `contract_start`, `contract_end`, `gross`, `insurence_cost1`, `insurence_cost2`, `to_payout`, `due`) VALUES
(1, 4, '2017-10-01', '2017-10-31', '1000.00', '137.10', '171.60', '768.24', '1171.60'),
(2, 4, '2017-10-01', '2017-10-31', '2000.00', '274.20', '392.20', '1459.48', '2392.20'),
(3, 15, '2017-08-01', '2017-09-08', '2000.00', '274.20', '392.20', '1418.88', '2392.20'),
(4, 17, '2017-08-01', '2017-09-08', '2000.00', '274.20', '392.20', '1459.48', '2392.20'),
(5, 9, '2017-08-01', '2017-09-08', '2826.12', '303.39', '433.95', '2058.08', '3260.07'),
(6, 11, '2017-08-01', '2017-09-08', '2000.00', '274.20', '392.20', '1459.48', '2392.20'),
(7, 5, '2017-08-01', '2017-09-08', '2000.00', '274.20', '392.20', '1418.88', '2392.20'),
(8, 6, '2017-08-01', '2017-09-08', '2000.00', '274.20', '392.20', '1459.48', '2392.20');

查询

set @dstart = "2017-10-01",@dend = "2017-10-30";

select employees_salaries.PK_worker , coalesce(sum(employees_salaries.gross),0) as p_am, coalesce(sum(insurence_cost1 + insurence_cost2),0) as incost
        from   employees_salaries 
        /* This example won't return reliable data
        WHERE    employees_salaries.contract_start      >= @dstart
        and    employees_salaries.contract_end <= @dend
        */
     GROUP BY employees_salaries.PK_worker

我正在努力完成以下结果:

方案

  • 我们设置查询的时间范围,显示@dstart = "2017-10-01",@dend = "2017-10-30";
  • 的工资

逻辑上应该 contract_start 应该在我们的 @dstart @dend 之间,

contract_end 也应该在 @dstart @dend 之间,但如果 contract_end 例如2017- 12-30?它会产生这样的逻辑

2017-10-01和2017-10-30之间是2017-12-30?答案是否定的,因为它更大。

它也可能适用于 contract_start :2017-09-01是2017-10-01和2017-10-30之间?不,但 contract_end 在范围内。

问题是如何实施这种情景?任何提示赞赏

MCVE https://www.db-fiddle.com/f/wAQ2eGfp2kCAdQ7QUBRYKp/3

1 个答案:

答案 0 :(得分:0)

set @dstart = "2017-10-01",@dend = "2017-10-30";

    select employees_salaries.PK_worker , coalesce(sum(employees_salaries.gross),0) as p_am, coalesce(sum(insurence_cost1 + insurence_cost2),0) as incost
            from   employees_salaries 

            WHERE
            @dstart BETWEEN employees_salaries.contract_start AND employees_salaries.contract_end 
   OR  @dend BETWEEN employees_salaries.contract_start AND employees_salaries.contract_end 
   OR @dstart >= employees_salaries.contract_start AND @dend <= employees_salaries.contract_end 


         GROUP BY employees_salaries.PK_worker