我有两张桌子
--
-- Table structure for table `d_statistics_report_temp`
--
CREATE TABLE IF NOT EXISTS `d_statistics_report_temp` (
`srt_id` int(10) NOT NULL AUTO_INCREMENT ,
`pub_name` varchar(100) DEFAULT NULL ,
`sal_must_pay_date` date DEFAULT NULL ,
`total_sales` float(7,0) DEFAULT NULL,
`total_must_pay` float(7,0) NOT NULL,
`pub_share` float(7,0) DEFAULT NULL ,
`pub_id` int(11) DEFAULT NULL COMMENT ,
`conversion_doc` varchar(255) NOT NULL,
PRIMARY KEY (`srt_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `d_statistics_report_temp`
--
INSERT INTO `d_statistics_report_temp`
(`srt_id`, `pub_name`, `sal_must_pay_date`, `total_sales`, `total_must_pay`, `pub_share`, `pub_id`, `conversion_doc`)
VALUES
(1, 'sara', '2013-03-01', 50, 0, 15, 256, ''),
(2, 'sara', '2013-04-01', 20, 0, 15, 256, ''),
(3, 'sara', '2013-05-01', 80, 0, 15, 256, ''),
(4, 'sara', '2013-06-01', 10, 0, 15, 256, ''),
(5, 'sara', '2013-07-01', 20, 0, 15, 256, ''),
(6, 'sara', '2013-08-01', 70, 0, 15, 256, ''),
(7, 'sara', '2013-09-01', 90, 0, 15, 256, ''),
(8, 'adam', '2013-05-01', 10, 0, 15, 255, '')
和第二个表
--
-- Table structure for table `d_statistics_docs`
--
CREATE TABLE IF NOT EXISTS `d_statistics_docs` (
`sd_id` int(11) NOT NULL AUTO_INCREMENT,
`sd_pub` int(11) NOT NULL,
`sd_date` date NOT NULL,
`sd_doc` text NOT NULL,
`price` int(11) NOT NULL,
PRIMARY KEY (`sd_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=16 ;
--
-- Dumping data for table `d_statistics_docs`
--
INSERT INTO `d_statistics_docs` (`sd_id`, `sd_pub`, `sd_date`, `sd_doc`, `price`) VALUES
(9, 256, '2013-03-01', 'scifiwallpaper1.jpg'),
(10, 256, '2013-04-01', 'scifiwallpaper1.jpg'),
(11, 256, '2013-05-01', ''),
(12, 256, '2013-06-01', 'scifiwallpaper1.jpg'),
(13, 256, '2013-07-01', ''),
(14, 256, '2013-08-01', ''),
(15, 256, '2013-09-01', 'scifiwallpaper1.jpg');
我想加入表格,为每total_sales
pub_id
(publisher_id)获取sd_date
但我想仅为此when sd_doc IS NULL
条件total_sales
获取sd_date
如果sd_doc NOT NULL
本月返回total_sales
且所有月份都在
输出示例
9 256 2013-03-01 scifiwallpaper1.jpg 50
10 256 2013-04-01 scifiwallpaper1.jpg 20
11 256 2013-05-01 NULL 80
12 256 2013-06-01 scifiwallpaper1.jpg 90 // total 10 + 80
13 256 2013-07-01 NULL 20
14 256 2013-08-01 NULL 70
15 256 2013-09-01 scifiwallpaper1.jpg 180 // total of 90+70+20
* 注意:第二个表格中的sal_must_pay_date = sd_date *
答案 0 :(得分:1)
您可以使用变量跟踪以前的行(只要您正确排序)。所以您的查询可以写成如下:
SET @i = 0.0;
SELECT rt.srt_id,
rt.pub_id,
d.sd_date,
CASE WHEN d.sd_doc != '' THEN d.sd_doc END sd_doc,
rt.total_sales,
@i + rt.total_sales AS Cumulative_Total,
@i:= CASE WHEN d.sd_doc = '' THEN @i + rt.total_sales ELSE 0 END AS Increment
FROM d_statistics_report_temp rt
INNER JOIN d_statistics_docs d
ON rt.pub_id = d.sd_pub
AND rt.sal_must_pay_date = d.sd_date
ORDER BY rt.pub_id, d.sd_date;
在这种情况下,变量@i对每行进行更改,如果sd_doc不为空,则重置为0;如果sd_doc为空,则重置为先前的数量。
<强> Example on SQL Fiddle 强>