2013-02-09 31 views
1

大家好我有两个表,即tblTechnologytblQuestions其中tblTechnology保存关于像Asp.net, c# and alltblQuestions技术信息持有QuestionID] ,[QuestionTitle] ,[QuestionDesc] ,[DatePosted] ,[UserName] ,[TechID] ,[viewCount] ,[ReplyCount]多个select语句得到期望的结果

信息最初我有一个书面一个存储过程来得到期望的结果,现在我想摆脱tblQuestions每种技术的最新插入的记录,这是我在tblquestion

enter image description here

数据

从这个我想从每个技术

这得到最后插入的问题ORDER BY Dateposted是我最初写

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

我希望我的QuestionTitle,DatePostedUsername包含在结果中,所以有人可以帮助我

回答

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 
+0

什么是'这里ties' – Dotnet 2013-02-09 11:04:04

+0

WITH TIES的意思是:指定其他行从与在顺序的相同值设置通过担任最后的柱基返回结果TOP n(PERCENT)行。 TOP ... WITH TIES只能在SELECT语句中指定,并且只有在指定ORDER BY子句的情况下才能指定。 – revoua 2013-02-09 11:07:43

+0

错误'消息209,级别16,状态1,行1 歧义列名'TechID'。 Msg 209,Level 16,State 1,Line 3 不明确的列名'TechID'.' – Dotnet 2013-02-09 11:08:45