我很难搞清楚这是一个日期/时间问题。 我的表(服务)具有以下结构:
ShopID | ServiceID | Datestart | Timeend | StatusID
1 | 100 | 2014-03-03 | 09:16:22 | 15
1 | 200 | 2014-03-03 | 10:16:22 | 15
2 | 300 | 2014-03-05 | 18:16:00 | 15
2 | 400 | 2014-03-05 | 15:30:48 | 0
3 | 500 | 2014-03-07 | 09:16:22 | 15
4 | 550 | 2014-03-07 | 09:50:10 | 15
目标是在2014年为每个ShopID 获取:
Basicaly最近的ServiceID,可以是最高(因此最新)的ServiceID,也可以是具有最新Datestart和最近Timeend的ServiceID。 所有结果都需要与StatusID = 15
这是我一直在使用的东西:
select max(ss.id), ss.shopid from service ss,
(select shopid, max(datestart) as datestart
from service s
where
statusid = 15 and
datestart between '2014-01-01' and '2014-12-31'
group by shopid) x
where ss.shopid=x.shopid and ss.statusid = 15 and ss.datestart=x.datestart group by ss.shopid
这适用于最近的ServiceID和Date,但我无法将TimeEnd放入其中。 希望任何人都可以帮忙解决这个问题。
答案 0 :(得分:0)
我只是在子查询和连接中包含了TimeEnd列:
SELECT
MAX(ss.id),
ss.shopid
FROM
service ss,
(
SELECT
shopid,
max(DATESTART) as DATESTART,
MAX(TIMEEND) as TIMEEND
FROM
service s
WHERE
statusid = 15
AND datestart BETWEEN '2014-01-01' AND '2014-12-31'
GROUP BY
SHOPID
)
X
WHERE
ss.shopid =x.shopid
AND ss.statusid = 15
AND SS.DATESTART=X.DATESTART
AND SS.TIMEEND=X.TIMEEND
GROUP BY
ss.shopid;