我正在尝试更改查询的布局,以便将搜索时间合并到一列,以便我可以按顺序在我们的网站上显示搜索结果。
任何帮助都非常感激。
代码:
Select
StVS.ID AS 'SessionID',
-- Search Details
StBe.Bedrooms AS 'Searches Bedrooms',
StDo.Dogs AS 'Searches Dogs',
StDu.Duration AS 'Searches Duration',
-- Search times
StBe.datetimeselected AS 'Bedrooms time',
StDo.datetimeselected AS 'Dogs time',
StDu.datetimeselected AS 'Duration time'
FROM Stats_VisitorSessions StVs
-- Searches
left join Stats_Bedrooms StBe on StBe.SessionID=StVS.SessionID
left join Stats_Dogs StDo on StDo.SessionID=StVS.SessionID
left join Stats_Duration StDu on StDu.SessionID=StVS.SessionID
答案 0 :(得分:1)
使用UNION:
Select
StVS.ID AS 'SessionID',
StBe.datetimeselected AS 'SearchTime',
StBe.Bedrooms AS Bedrooms,
NULL as Dogs,
NULL as Duration
FROM Stats_VisitorSessions StVs
left join Stats_Bedrooms StBe on StBe.SessionID=StVS.SessionID
UNION ALL
Select
StVS.ID AS 'SessionID',
StDo.datetimeselected AS 'SearchTime',
NULL AS Bedrooms,
StDo.Dogs as Dogs,
NULL as Duration
FROM Stats_VisitorSessions StVs
left join Stats_Dogs StDo on StDo.SessionID=StVS.SessionID
UNION ALL
Select
StVS.ID AS 'SessionID',
StDu.datetimeselected AS 'SearchTime',
NULL AS Bedrooms,
NULL as Dogs,
StDu.Duration as Duration
FROM Stats_VisitorSessions StVs
left join Stats_Duration StDu on StDu.SessionID=StVS.SessionID
答案 1 :(得分:0)
SELECT t.SessionID, t1./dog-rel info/, t1./bedroom-rel info/, t1./dur-rel info/ FROM Table t
INNER JOIN (
SELECT SessionID, /dog related into/ and nulls for other info
UNION ALL
SELECT SessionID, nulls for dog, /bedrom related into/, nulls for duration
UNION ALL
SELECT SessionID, nulls for all above, /duration related into/
) t1 ON (t.SessionId = t1.SessionId)
也可以使用3个左外连接
SELECT t.SessionID, t1./dogs rel info/, t2./bedroom rel info/, t3./duration rel info/ FROM Table t
LEFT OUTER JOIN Table as t1 ON (t.SessionId = t1.SessionId)
LEFT OUTER JOIN Table as t2 ON (t.SessionId = t2.SessionId)
LEFT OUTER JOIN Table as t3 ON (t.SessionId = t3.SessionId)