簡體   English   中英

使用內部聯接時具有不同值的SQL查詢

[英]SQL query with distinct values while using inner join

避免以前發布的問題。

我正在使用內部lotid表, lotiddate來自test表,而worker程序來自test1表。 我正在使用group by但由於工作人員和日期列不同,因此無法正常工作

lotid worker date
1234  abc    02/02/2106
1234  xyz    03/03/2016

但在輸出中我應該只得到1個lotid

lotid worker date
1234   abc   02/02/2016

如何實現?

我使簡單的表和簡單的查詢使用下面的DENSE_RANK()

CREATE TABLE #test (lotid NVARCHAR(10), workDate DATETIME)
CREATE TABLE #test1 (lotid NVARCHAR(10),worker NVARCHAR(10) )

INSERT INTO #test VALUES ('1234','2016-02-02'),('1234','2016-03-03')

INSERT INTO #test1 VALUES ('1234','abc'),('1234','xyz')


SELECT *
FROM (
    SELECT DISTINCT t.*
        ,DENSE_RANK() OVER (PARTITION BY t.lotid ORDER BY t.workDate ASC) AS [r]
    FROM #test t 
    INNER JOIN #test1 t1 ON t.lotid = t1.lotid
) q
WHERE q.r = 1

DROP TABLE #test
DROP TABLE #test1

結果是:

lotid | 工作日期| [R

1234 | 2016-02-02 00:00:00.000 | 1

感謝您的所有幫助,但我想出了解決方案,

select lotid,
max(worker) as worker
max(trsdate) as max_date
from test
inner join test1
on test.lotid=test1.lotid
group by lotid

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM