[英]SQL Inner Join using Distinct and Order by Desc
table a. 表a。 Table b . 表b。 I have two tables. 我有两张桌子。 Table A has over 8000+ records and continues to grow with time. 表A具有8000多个记录,并且随着时间的推移持续增长。 Table B has only 5 or so records and grows rarely but does grow sometimes. 表B只有5条左右的记录,很少增长,但有时确实会增长。
I want to query Table A's last records where the Id for Table A matches for Table B. The problem is; 我想查询表A的最后一条记录,其中表A的ID与表B的匹配。 I am getting all the rows from Table A. I just need the ones where Table A and B match once. 我从表A中获得所有行。我只需要表A和B匹配一次的行。 These are unique Id's when a new row is inserted into table B and never get repeated. 当在表B中插入新行且永不重复时,这些是唯一的ID。
Any help is most appreciated. 非常感谢您的帮助。
SELECT a.nshift,
a.loeeworkcellid,
b.loeeconfigworkcellid,
b.loeescheduleid,
b.sdescription,
b.sshortname
FROM oeeworkcell a
INNER JOIN dbo.oeeconfigworkcell b
ON a.loeeconfigworkcellid = b.loeeconfigworkcellid
ORDER BY a.loeeworkcellid DESC
I am assuming you want to get the only the lastest
(as you said) row from the TableA
but JOIN
giving you all the rows.You can use the Row_Number() to get the rownumber and then apply the join and filter it with the Where
clause to select only the first row from the JOIN
. 我假设你想要得到的唯一的lastest
从(如你所说)排TableA
,但JOIN
给你所有的rows.You可以使用ROW_NUMBER()来获取ROWNUMBER,然后应用加入,并与过滤它Where
子句从JOIN
只选择第一行。 So what you can try as below, 因此,您可以尝试以下操作,
;WITH CTE
AS
(
SELECT * , ROW_NUMBER() OVER(PARTITION BY loeeconfigworkcellid ORDER BY loeeworkcellid desc) AS Rn
FROM oeeworkcell
)
SELECT a.nshift,
a.loeeworkcellid,
b.loeecoonfigworkcellid,
b.loeescheduleid,
b.sdescription,
b.sshortname
FROM CTE a
INNER JOIN dbo.oeeconfigworkcell b
ON a.loeeconfigworkcellid = b.loeeconfigworkcellid
WHERE
a.Rn = 1
You need to group by your data and select only the data having the condition with min id. 您需要按数据分组,并仅选择具有最小ID条件的数据。
SELECT a.nshift,
a.loeeworkcellid,
b.loeecoonfigworkcellid,
b.loeescheduleid,
b.sdescription,
b.sshortname
FROM oeeworkcell a
INNER JOIN dbo.oeeconfigworkcell b
ON a.loeeconfigworkcellid = b.loeeconfigworkcellid
group by
a.nshift,
a.loeeworkcellid,
b.loeecoonfigworkcellid,
b.loeescheduleid,
b.sdescription,
b.sshortname
having a.loeeworkcellid = min(a.loeeworkcellid)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.