【发布时间】:2017-11-22 05:51:27
【问题描述】:
我有 2 个选择查询,我想加入一个没有重复的查询。此外,我想使用在所有表中找到的 shiftindex 主键加入他们。我该怎么做?
第一个选择语句是:
SELECT dbo.hist_exproot.year,
dbo.hist_exproot.[month#],
dbo.hist_exproot.month,
dbo.hist_exproot.day,
dbo.hist_exproot.[shift#],
dbo.hist_exproot.shift,
dbo.hist_loads.excav,
SUM(dbo.hist_loads.loadtons) AS 'TONS',
SUM(dbo.hist_loads.ex_tmcat00)/3600 AS 'TTOTAL',
SUM(dbo.hist_loads.ex_tmcat01+dbo.hist_loads.ex_tmcat02)/3600 AS 'T_EFECT'
FROM dbo.hist_exproot
INNER JOIN dbo.hist_loads
ON dbo.hist_exproot.shiftindex = dbo.hist_loads.shiftindex
WHERE (dbo.hist_exproot.year >= 16)
GROUP BY dbo.hist_exproot.year,
dbo.hist_exproot.[month#],
dbo.hist_exproot.month,
dbo.hist_exproot.day,
dbo.hist_exproot.[shift#],
dbo.hist_exproot.shift,
dbo.hist_loads.excav
第二个是:
SELECT dbo.hist_exproot.year,
dbo.hist_exproot.[month#],
dbo.hist_exproot.shiftdate,
dbo.hist_exproot.shift,
dbo.hist_statusevents.eqmt,
dbo.hist_exproot.crew,
dbo.hist_reasontable.category,
dbo.hist_statusevents.reason,
dbo.hist_reasontable.name,
dbo.hist_operlist.operid,
dbo.hist_statusevents.starttime,
dbo.hist_statusevents.endtime,
dbo.hist_statusevents.duration/3600 as 'Time',
dbo.hist_statusevents.comment
FROM dbo.hist_reasontable
INNER JOIN dbo.hist_statusevents
ON dbo.hist_reasontable.shiftindex = dbo.hist_statusevents.shiftindex
AND dbo.hist_reasontable.reason = dbo.hist_statusevents.reason
INNER JOIN dbo.hist_operlist
ON dbo.hist_statusevents.operid = dbo.hist_operlist.operid
AND dbo.hist_statusevents.shiftindex = dbo.hist_operlist.shiftindex
AND dbo.hist_reasontable.shiftindex = dbo.hist_operlist.shiftindex
INNER JOIN dbo.hist_exproot
ON dbo.hist_statusevents.shiftindex = dbo.hist_exproot.shiftindex
WHERE
(dbo.hist_exproot.year >= 16)
AND (dbo.hist_statusevents.unit = 2)
AND(dbo.hist_statusevents.eqmt <> 'L98')
AND (dbo.hist_statusevents.eqmt <> 'L96')
AND (dbo.hist_statusevents.eqmt <> 'L09')
AND (dbo.hist_statusevents.eqmt <> 'S47')
ORDER BY dbo.hist_exproot.shiftdate,
dbo.hist_statusevents.eqmt
如果您有任何问题,请告诉我。
谢谢
【问题讨论】:
-
除非您实际上以某种方式使用 MySQL,否则
mysql标签可能不适用,应该删除。 -
您迫切需要使用别名。这个查询读起来简直是噩梦。
-
假设这确实是 T-SQL,CTE 是你的朋友,无论查询多么不可读。
WITH T1 AS (SELECT ...), T2 AS (SELECT ...) SELECT * FROM T1 JOIN T2 ON ...。不过,子查询中的ORDER BY子句需要删除。
标签: mysql sql-server tsql