我正在尝试从3个表格中生成“历史/日志页面”,表格如下所示:
CreationDate
ModifDate
LastAccessedDate
FileName
Guid_TableA
CreationDate
ModifDate
LastAccessedDate
FileName
Guid_TableA
LastModifDate
FileName
FWIW,尽管列名相似,这些表中的日期之间没有关系。唯一有效的列是 Guid_TableA
选择记录&按日期订购。 我正在尝试构建一个事件日志,因此返回这样的重复条目是有效的(只要结果按日期正确排序)
(TableA) file-1.txt '01/01/2012 00:00:00' (CreationDate)
(TableA) file-1.txt '01/01/2012 00:00:01' (ModifDate)
(TableB) file-2.txt '01/01/2012 00:00:02' (CreationDate)
(TableA) file-1.txt '01/01/2012 00:00:03' (LastAccessedDate)
希望我的意图很明确;我基本上想要选择按日期排序的记录(即,针对多个交叉表列进行排序,包括重复的条目)
我的问题是:这可能吗?如果是这样,怎么样?
答案 0 :(得分:3)
您希望使用UNION ALL
运算符合并多个选择的结果:
SELECT FileName, CreationDate AS Date FROM TableA
UNION ALL SELECT FileName, ModifDate FROM TableA
UNION ALL SELECT FileName, LastAccessDate FROM TableA
UNION ALL SELECT FileName, CreationDate FROM TableB
-- ...etc
ORDER BY Date;
如果你想要那些“TableA”和“CreationDate”注释,你也可以添加它们作为文字字符串:
SELECT 'TableA', FileName, CreationDate AS Date, 'CreationDate' FROM TableA
UNION ALL SELECT 'TableA', FileName, ModifDate, 'ModifDate' FROM TableA
UNION ALL SELECT 'TableA', FileName, LastAccessDate, 'LastAccessDate' FROM TableA
UNION ALL SELECT 'TableB', FileName, CreationDate, 'CreationDate' FROM TableB
-- ...etc
ORDER BY Date;
这给了我:
TableA|file-1.txt|01/01/2012 00:00:00|CreationDate
TableA|file-1.txt|01/01/2012 00:00:01|ModifDate
TableB|file-2.txt|01/01/2012 00:00:02|CreationDate
TableA|file-1.txt|01/01/2012 00:00:03|LastAccessDate