简体   繁体   中英

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? (Basically I only need the type and related field which is not 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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