在sql server中,我有一个带有此结构的表(userMessageTbl)
User UserMessage UserMessageDate AdminMessage AdminMessageDate
现在我希望按日期UserMessage
从此表中选择AdminMessageDate
和DES
。
例如
User UserMessage UserMessageDate AdminMessage AdminMessageDate
test hi 2015-03-1 thanks 2015-10-4
test ok 2015-08-2 car 2015-09-1
test u 2015-10-2 book 2015-10-3
我想得到这个:
thanks
book
u
car
ok
hi
感谢您的帮助
答案 0 :(得分:1)
在派生表中执行UNION ALL
。然后订购结果。
select msg from
(
select UserMessage as msg, UserMessageDate as msgdate from table
union all
select AdminMessage as msg, AdminMessageDate as msgdate from table
) as dt
order by msgdate
答案 1 :(得分:1)
; WITH MD AS
(
SELECT UserMessage AS [Message], UserMessageDate AS [Date] FROM userMessageTbl
UNION ALL
SELECT AdminMessage AS [Message], AdminMessageDate AS [Date] FROM userMessageTbl
)
SELECT [Message], [Date] FROM
MD
ORDER BY [Date] DESC
答案 2 :(得分:0)
通过使用Cross Apply,Co-related Subquery和Order by我们也可以实现这个
Select val from (
select val,dval from table1
CROSS APPLY (values ('UserMessage',UserMessage),
('AdminMessage',AdminMessage))cs(col,val)
CROSS APPLY (values ('UserMessageDate',UserMessageDate),
('AdminMessageDate',AdminMessageDate))vs(dcol,dval) )T
ORDER BY T.dval Desc