我正在使用两个名为Transactions和Items的表。请参阅下文
表1:交易
C_ID - State - Time
1 Start 2016-07-13 16:02:42
1 Passed 2016-07-13 20:28:21
2 Passed 2016-07-11 17:39:13
3 Passed 2016-07-07 20:23:00
4 Start 2016-07-01 13:19:54
4 Passed 2016-07-01 17:37:41
5 Start 2016-07-07 16:16:21
5 Passed 2016-07-07 21:04:01
6 Passed 2016-07-07 21:11:39
7 Passed 2016-07-08 20:30:46
表2:项目
C_No - C_ID
C1 - 5
C2 - 3
C3 - 9
C4 - 7
C5 - 6
C6 - 8
C7 - 2
C8 - 4
C9 - 10
C10 - 1
我想加入这些表并需要输出如下所述;
输出
C_No - State - Time
C10 - Start 2016-07-13 16:02:42
C10 - Passed 2016-07-13 20:28:21
C8 - Start 2016-07-01 13:19:54
C8 - Passed 2016-07-01 17:37:41
C1 - Start 2016-07-07 16:16:21
C1 - Passed 2016-07-07 20:00:01
除了连接两个表,我想要一个State和Time的过滤器。条件是(州='开始'和时间< = 17:00)和(州='通过'和时间< = 21:00)
我不希望任何项目都没有“开始”和“通过”。
我使用了以下查询
{SELECT distinct(c.C_No), p.State, p.Time FROM Items c
inner join Transitions p on p.c_id = c.c_id and date(p.Time) between '2016-07-01' and CURRENT_DATE()
and ((p.State = 'Start' and time(p.Time) <= '17:00:00') or p.State = 'Passed' )
order by c.C_No, State;}
SQLFiddle已添加到问题中。
答案 0 :(得分:0)
试试这句话
从transactions.c_id = items.c_id中的事务内连接项中选择c_no,state,time其中(state ='Start'和right(time,8)&lt; ='17:00:00')或(state ='通过'和右(时间,8)&lt; ='21:00:00')
答案 1 :(得分:0)
想法如下:
with t_start as (
select t2.c_no, t1.state, t1.time
from transactions t1
inner join items t2 on t2.c_id=t1.c_id
where t1.state='State' and time(t1.time)<='17:00:00'
) t_passed as(
select t2.c_no, t1.state, t1.time
from transactions t1
inner join items t2 on t2.c_id=t1.c_id
where t1.state='Passed' and time(t1.time)<='21:00:00'
) t_total as(
select * from t_start
union
select * from t_passed
)
select * from t_total order by c_no, state;
答案 2 :(得分:0)
在您的问题中,对于您的示例数据,我认为结果中不应存在C1
,因为当C_ID
= 5时,其State
为'已通过'且其Time
是'2016-07-07 21:04:01',它与您的情况不符。所以试试这个:
select t2.C_No, t.`State`, t.`Time`
from Transactions t
join (
select C_ID
from Transactions
where (State = 'Start' and time(`Time`) <= '17:00:00')
or (State = 'Passed' and time(`Time`) <= '21:00:00')
group by C_ID
having count(distinct State) > 1
) t1 on t.C_ID = t1.C_ID
left join Items t2 on t1.C_ID = t2.C_ID
order by t2.C_No, t.`State`;