我有两个问题:
SELECT
b.ref,
ts.id_baits,
SUM(strftime('%s',ts.endtime) -strftime('%s',ts.initime)) AS t,COUNT(*) AS n
FROM TimeSegments AS ts
INNER JOIN Baits AS b ON b.id = ts.Id_Baits
GROUP BY ts.id_baits
ORDER BY b.ref
SELECT b.ref,
COUNT(CASE WHEN e.Status=1 THEN 1 END) AS Undefined,
COUNT(CASE WHEN e.Status=1 THEN 1 END) AS GetClose,
COUNT(CASE WHEN e.Status=2 THEN 1 END) AS Threat,
COUNT(CASE WHEN e.Status=3 THEN 1 END) AS Attack,
COUNT(CASE WHEN e.Status=4 THEN 1 END) AS Hooked,
COUNT(CASE WHEN e.Status=5 THEN 1 END) AS Captured,
COUNT(CASE WHEN e.Status=6 THEN 1 END) AS Tagged,
COUNT (*) AS TOTAL
FROM CastingsEvents AS e
LEFT JOIN Trajectories AS tr ON tr.id = e.id_trajectories
LEFT JOIN TimeSegments AS ts ON ts.id = tr.id_timesegments
LEFT JOIN Baits AS b ON b.id = ts.Id_Baits
GROUP BY ts.id_baits
ORDER BY b.ref
如图所示,两个表都按id_baits分组。
我想将结果合并到一个表中,有人知道该怎么做吗?
答案 0 :(得分:0)
根据提议(JOIN two SELECT statement results),LEFT JOIN解决问题:
SELECT * FROM (
SELECT
b.ref AS bait,
ts.id_baits,
SUM(strftime('%s',ts.endtime) -strftime('%s',ts.initime)) AS t,
COUNT(*) AS n
FROM TimeSegments as ts
INNER JOIN Baits as b ON b.id = ts.id_baits
GROUP BY ts.id_baits
) BaitsUsage
LEFT JOIN (
SELECT
ts.id_baits,
COUNT(CASE WHEN e.Status=1 THEN 1 END) AS Undefined,
COUNT(CASE WHEN e.Status=1 THEN 1 END) AS GetClose,
COUNT(CASE WHEN e.Status=2 THEN 1 END) AS Threat,
COUNT(CASE WHEN e.Status=3 THEN 1 END) AS Attack,
COUNT(CASE WHEN e.Status=4 THEN 1 END) AS Hooked,
COUNT(CASE WHEN e.Status=5 THEN 1 END) AS Captured,
COUNT(CASE WHEN e.Status=6 THEN 1 END) AS Tagged,
COUNT (*) AS TOTAL
FROM CastingsEvents AS e
LEFT JOIN Trajectories AS tr ON tr.id = e.id_trajectories
LEFT JOIN TimeSegments AS ts ON ts.id = tr.id_timesegments
LEFT JOIN Baits AS b ON b.id = ts.Id_Baits
GROUP BY ts.id_baits
) BaitsEvents
ON BaitsUsage.id_baits=BaitsEvents.id_baits
ORDER BY bait