2016-10-17 132 views
2

表1SQL服務器不同行上連接

id mobile uid uniqueid time 

1 9999 1232 200100 10/6/15 

2 9999 1232 200100 11/5/14 

3 8888 1232 200100 18/4/16 

4 9999 1232 200100 07/7/15 

5 9999 1232 200100 4/11/16 

表2

id Qid account 

1 200100 123456 

2 200100 123456 

3 200100 123456 

我根據移動號碼

我使用的查詢等

想僅非重複數據
SELECT R.Id,R.MobileNo,R.UId,R.UniqueId,R.Time, 
ISNULL(C.account,'Not Present'), 
FROM table1 R LEFT JOIN table2 C 
ON R.uniqueId=C.QId where 
and R.deleteStatus='Y' and C.accountNos ='123456' 

慾望輸出是

mobile uid uniqueid time account 
9999 1232 200100 4/11/16 123456 
8888 1232 200100 18/4/16 123456 

我試過在sql server的每一件事情,但不能得到慾望輸出請幫助我!!!!!

+1

聽起來像是你應該閱讀有關聚集。提示.... MAX(時間)。 FWIW,您的示例查詢中的列不在您的示例數據中。另外,我猜測「時間」是某種日期的表示形式? –

回答

0

試試這個:這會給最新的數據表

SELECT R.Id,R.MobileNo,R.UId,R.UniqueId,MAX(R.Time),ISNULL(C.account,'Not Present'), 
FROM table1 R 
LEFT JOIN table2 C ON R.uniqueId=C.QId AND C.accountNos ='123456' 
WHERE R.deleteStatus='Y' 
GROUP BY R.Id,R.MobileNo,R.UId,R.UniqueId,ISNULL(C.account,'Not Present') 
+0

當我觸發此查詢時,它會生成以下錯誤 – KD11

+0

列'Id'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 – KD11

+0

已經嘗試過精確的腳本,即我使用了aggrigate函數'MAX(R.Time)' –

0

請試試這個:

with cte as (
    SELECT 
     R.Id, 
     R.MobileNo, 
     R.UId, 
     R.UniqueId, 
     R.Time, 
     ISNULL(C.account,'Not Present'), 
     Row_Number() Over(Partition by R.MobileNo order by [time] Desc) as RN 
    FROM table1 R 
    LEFT JOIN table2 C 
     ON R.uniqueId=C.QId 
    where 
     R.deleteStatus='Y' and C.accountNos ='123456' 
) 
    Select * from cte 
    Where rn=1 
+0

是否有任何其他替代方案,因爲我不能改變我的機器100兼容模式爲90其他事情受到影響 – KD11

+0

我不認爲你需要降級你的數據庫級別,因爲「與公用表表達式」和「Row_Number 「在2008年及以上得到支持。 –

+0

此查詢運行罰款,但在輸出它不顯示數據只有空白列顯示 – KD11

0
CREATE TABLE #TABLE1 
(


ID INT, MOBILE INT, UID INT, UNIQUEID INT, TIME DATE 
) 


INSERT INTO #TABLE1 VALUES(1,9999,1232,200100,'6-10-15') 
INSERT INTO #TABLE1 VALUES(2,9999,1232,200100,'5-11-14') 
INSERT INTO #TABLE1 VALUES(3,8888,1232,200100,'4-18-16') 
INSERT INTO #TABLE1 VALUES(4,9999,1232,200100,'7-7-15') 
INSERT INTO #TABLE1 VALUES(5,9999,1232,200100,'11-4-16') 


SELECT * FROM #TABLE1 

CREATE TABLE #B 
(
ID INT, QID INT, ACCOUNT INT) 
INSERT INTO #B VALUES 

(1,200100,123456), 
(2,200100,123456), 
(3,200100,123456) 


;WITH CTE AS 
(

SELECT DISTINCT T1.MOBILE,UID,UNIQUEID,TIME,ACCOUNT, 
ROW_NUMBER() OVER(PARTITION BY MOBILE ORDER BY [TIME] DESC) AS RN 
FROM #TABLE1 T1 JOIN #B T2 ON T1.ID=T1.ID 
AND T1.UNIQUEID=T2.QID 

) 
SELECT MOBILE,UID,UNIQUEID,TIME,ACCOUNT 

FROM CTE 
WHERE RN=1