2013-02-09 66 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