简体   繁体   English

SQL Server在单个查询中返回多个查询

[英]SQL Server return multiple queries in a single query

I have the following table 我有下表

ID      TYPE        Text       ImagePath     Title    Date

 1      Text        Test        NULL          NULL     14/10/2013
 2      Image       NULL        /test/test    NULL     14/10/2013
 3      Title       NULL        NULL          Test     14/10/2013
 4      Text        Test2       NULL          NULL     20/12/2012

How can I retrieve ONLY the last 3 (sorted by date) records, 1 with type Text, 1 with type Image and 1 with type Title only? 我如何仅检索最后3条记录(按日期排序),1条文本类型,1条图像类型和1条标题类型? (Basically I only need the type and related field which is not NULL. (基本上,我只需要类型和相关字段不为NULL。

Apart from restructuring your database as I said in the comment on your question, this should give you what you want (if I understood the question properly): 除了按照我在对问题的评论中所说的那样重组数据库之外,这还应该为您提供所需的信息(如果我对问题的理解正确):

SELECT
TOP 1 
'Text' AS Type,
Text
FROM
your_table
ORDER BY Date DESC
UNION ALL
SELECT
TOP 1 
'ImagePath',
ImagePath
FROM
your_table
ORDER BY Date DESC
UNION ALL
SELECT
'Title', 
TOP 1 Title
FROM
your_table
ORDER BY Date DESC

You may have to put some parantheses here and there to make it work... 为了使它起作用,您可能不得不在这里和那里放一些寄生物。

One idea could be: 一种想法可能是:

SELECT  * FROM table where TYPE = 'Text' OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY 
union
SELECT  * FROM table where TYPE = 'Image' OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY 
union
SELECT  * FROM table where TYPE = 'Title' OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM