我有一个Mysql数据库,我有两个表格,其架构为:
CREATE TABLE IF NOT EXISTS `items` (
`id` int(10) unsigned NOT NULL,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `sold_records` (
`id` int(10) unsigned NOT NULL,
`item_id` int(10) NOT NULL,
`count` int(10) NOT NULL,
`sold_at` timestamp NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
如您所见,我有一些项目和一些销售记录,我希望通过SQL查询得到这样的结果:
item_name sold_count_at_today sold_count_at_yestoday ... sold_count_at_today - 30day
item_1 x x ... x
item_2 x x ... x
...
item_n x x ... x
有人可以就SQL查询得到这样的结果提出一些建议吗?
您可以在SQLFiddle。
中对其进行调试答案 0 :(得分:1)
不幸的是,我认为你必须用一堆案例函数来做这件事,比如:
SELECT i.name,
CASE WHEN CAST(sold_at AS date) = '2017-10-31' THEN 'X' ELSE NULL END AS '2017-10-31',
CASE WHEN CAST(sold_at AS date) = '2017-11-01' THEN 'X' ELSE NULL END AS '2017-11-01'
...
FROM items i
INNER JOIN sold_records r
ON i.id = r.item_id
我在你设置的小提琴上试过这个。你可以在这里查看:
答案 1 :(得分:1)
select a.name as item_name,
count(b.sold_at = (DATE_FORMAT(FROM_UNIXTIME(current_timestamp), '%e %b %Y'))) as
sold_count_at_today,
count((b.sold_at = (DATE_FORMAT(FROM_UNIXTIME(current_timestamp -1), '%e %b %Y')))) as sold_count_at_yesterday,
count((b.sold_at = (DATE_FORMAT(FROM_UNIXTIME(current_timestamp- 30), '%e %b %Y')))) as 30_day
from items a, sold_records b
where a.id = b.item_id
group by a.name;
试试这个。 http://sqlfiddle.com/#!9/92f796/23/0假设今天是当前的时间戳。