我有下表:
表格1:
CREATE TABLE table1
(
id int auto_increment primary key,
person varchar(30),
color_code varchar(30),
item_id varchar(30),
date_start DATE,
date_complete DATE
);
INSERT INTO table1
(person, color_code, item_id, date_start, date_complete)
VALUES
('Jackson', 'RED', '1', '2013-07-11 11:23:39', '2013-08-1 11:23:39'),
('Danny', 'BLUE', '2', '2013-07-20 11:23:39', '2013-08-1 11:23:39'),
('Jimmy', 'GREEN', '5', '2013-05-15 11:23:39', '2013-08-1 11:23:39'),
('Jackson', 'RED', '3', '2013-02-16 11:23:39', '2013-08-1 11:23:39'),
('Jimmy', 'BLUE', '4', '2013-03-13 11:23:39', '2013-08-1 11:23:39'),
('William', 'RED', '5', '2013-04-29 11:23:39', '2013-08-1 11:23:39'),
('William', 'BLUE', '1', '2013-05-9 11:23:39', '2013-08-1 11:23:39'),
('Danny', 'GREEN', '5', '2013-01-6 11:23:39', '2013-08-1 11:23:39'),
('Jackson', 'RED', '4', '2013-07-11 11:23:39', '2013-08-1 11:23:39'),
('Jackson', 'RED', '5', '2013-08-7 11:23:39', '2013-09-1 11:23:39');
表2:
CREATE TABLE table2
(
id int auto_increment primary key,
item_code varchar(30),
item_name varchar(30)
);
INSERT INTO table2
(item_code, item_name)
VALUES
('1', 'APPLE'),
('2', 'BANANA'),
('3', 'PINEAPPLE'),
('4', 'WATERMELON'),
('5', 'GUAVA');
我的 sql 查询如下所示:
SELECT
person AS 'Name',
COUNT(*) AS 'Total Item Purchased',
SUM(CASE WHEN (color_code='RED') THEN 1 ELSE 0 END) AS 'Total Red Color',
SUM(CASE WHEN (color_code='BLUE') THEN 1 ELSE 0 END) AS 'Total Blue Color',
SUM(CASE WHEN (color_code='GREEN') THEN 1 ELSE 0 END) AS 'Total Green Color',
SUM(CASE WHEN DATEDIFF(date_complete, date_start) BETWEEN 1 AND 30 THEN 1 ELSE 0 END) AS 'Bought Between 1-30 Days'
FROM table1
WHERE
person LIKE '%Jackson%' OR
person LIKE '%Danny%' OR
person LIKE '%Jimmy%' OR
person LIKE '%William%'
GROUP BY person;
问题:如何将table2中的item_name显示到包含所有行组的 select 查询中?我正在考虑子选择,在“在 1-30 天之间购买”之后有可能吗?
SQLFiddle:http ://sqlfiddle.com/#!2/d59e0/4