存储过程中的多个select语句以获得所需的结果

时间:2013-02-09 10:22:31

标签: sql sql-server-2008

大家好我有两个表tblTechnologytblQuestions,其中tblTechnology包含有关Asp.net, c# and alltblQuestions等技术的信息,其中包含QuestionID] ,[QuestionTitle] ,[QuestionDesc] ,[DatePosted] ,[UserName] ,[TechID] ,[viewCount] ,[ReplyCount]tblQuestions等信息。 {1}}

最初我有一个写入存储过程来获得所需的结果现在我想从tblquestion获取每个技术的最新插入记录,这是我在 SELECT TechName,TechDesc, tblTechnology.TechID as ID, COUNT(QuestionDesc) AS 'Totalposts',sum(ReplyCount) as ReplyCount FROM tblTechnology LEFT JOIN tblQuestions ON tblQuestions.TechID = tblTechnology.TechID GROUP BY tblTechnology.TechID, TechName,TechDesc

中的数据

enter image description here

从此我想得到最后插入的问题ORDER BY Dateposted from each technology

这是我最初写的

QuestionTitle

给出如下结果

enter image description here

我希望我的DatePostedUsername和{{1}}包含在结果中,以便有人帮助我

1 个答案:

答案 0 :(得分:3)

http://www.sqlfiddle.com/#!3/f5fe6/5

WITH A AS (
    SELECT top(1) WITH ties Q.TechID
        ,QuestionID
        ,QuestionTitle
        ,DatePosted
        ,Username
    FROM tblTechnology T LEFT JOIN tblQuestions Q ON Q.TechID = T.TechID
    ORDER BY row_number() over(partition BY Q.TechID ORDER BY Dateposted DESC)
)
SELECT * FROM A
OUTER apply (SELECT count(QuestionDesc) Totalposts, sum(ReplyCount) ReplyCount
    FROM tblQuestions WHERE A.TechID=tblQuestions.TechID) D