2011-06-22 64 views
-1
declare @userid int 
set @userid=9846 
SELECT TOP 10 
      tagid, 
      [Description] 
FROM tagsuggestion 
WHERE tagid IN (SELECT **DISTINCT** TOP 10 tagid 
      FROM (SELECT ulpt.tagid, 
          createddate 
        FROM userlocationposttag ulpt 
          WHERE [email protected]         

        UNION ALL 
        SELECT ult.tagid, 
          createddate 
        FROM userlocationtag ult 
          WHERE [email protected] 
        UNION ALL 
        SELECT upt.tagid, 
          createddate 
        FROM userprofiletag upt 
          WHERE [email protected] 
) T 

      ORDER BY createddate DESC) 

上述查詢是錯誤的如果指定了SELECT DISTINCT,ORDER BY項必須出現在選擇列表中。如果指定SELECT DISTINCT,則ORDER BY項必須出現在選擇列表中

。但如果我刪除DISTINCT這個查詢運行

我要保證清晰度,我也想通過createddate DESC保持排序順序

我相關聯的支柱之一是

Last created 10 records from all of the 3 tables

+0

「ORDER BY項目必須出現在選擇列表中,如果指定了SELECT DISTINCT「 - 你會意識到,如果像你說的那樣刪除** DISTINCT **,那麼這個短語不再適用...(如果指定了Y,那麼X是必需的 - 已刪除Y) –

+0

另外,SQL Server的版本是什麼? –

+0

所以你的第一個問題是誤導你的*實際*問題? – gbn

回答

1

好了,所以我們只關心此基礎上每個標籤的最新創建日期,所以我們就可以構建內部查詢爲:

SELECT tagid,MAX(createddate) as createddate FROM (
SELECT ulpt.tagid, 
     createddate 
FROM userlocationposttag ulpt 
WHERE [email protected]         
UNION ALL 
SELECT ult.tagid, 
     createddate 
FROM userlocationtag ult 
WHERE [email protected] 
UNION ALL 
SELECT upt.tagid, 
     createddate 
FROM userprofiletag upt 
WHERE [email protected] 
) t 
GROUP BY tagid 

,然後我們可以換,在另一個子選擇,並應用前十名:

SELECT TOP 10 tagid FROM (
SELECT tagid,MAX(createddate) as createddate FROM (
SELECT ulpt.tagid, 
     createddate 
FROM userlocationposttag ulpt 
WHERE [email protected]         
UNION ALL 
SELECT ult.tagid, 
     createddate 
FROM userlocationtag ult 
WHERE [email protected] 
UNION ALL 
SELECT upt.tagid, 
     createddate 
FROM userprofiletag upt 
WHERE [email protected] 
) t 
GROUP BY tagid 
) t ORDER BY createddate desc 

而且我們不再需要不同的(因爲GROUP BYMAX已經確保了每個標籤只出現一次)

2

你基本上是通過告訴查詢按照不存在的字段對輸出進行排序。

您必須將createddate放置在select語句中,或者可以按tagid,[Description]和createddate進行分組,並按createddate排序。

現在,如果您覺得在包含distinct created日期時可能會獲得重複的標記和說明,那麼請圍繞該日期換一個查詢,並在這兩個字段上做前10個不同的查詢。

+0

+1不錯的短語 – gbn

相關問題