[英]Sub-query returning more than 1 row: SQL Server
Sub-query returning more than 1 row.返回多于 1 行的子查询。
My current SQL Server query looks like this我当前的 SQL 服务器查询如下所示
SELECT DISTINCT AST.AssetName
,ReleaseDt
,ExpiresDt
,TicketNumber
,ChangeDt
,ChangeReasonCd
FROM pmm.pmmreleaserequest PRR WITH (NOLOCK)
LEFT JOIN pmm.PmmManagedAccount AS PMA WITH (NOLOCK) ON PRR.ManagedAccountID = PMA.ManagedAccountID
LEFT JOIN dbo.ManagedEntity AS ME WITH (NOLOCK) ON PRR.ManagedSystemID = ME.ManagedEntityID
LEFT JOIN dbo.Asset AS AST WITH (NOLOCK) ON ME.AssetID = AST.AssetID
LEFT JOIN pmm.PmmLogChange AS PLC WITH (NOLOCK) ON PRR.ManagedAccountID = PLC.ManagedAccountID
AND PRR.ExpiresDt < PLC.ChangeDt
ORDER BY PLC.ChangeDt ASC
And currently my output looks like as below.目前我的 output 如下所示。
AssetName ReleaseDt ExpiresDt TicketNumber ChangeDt ChangeReasonCd
DummyAsset66 2020-05-02 17:45:38 2020-05-02 17:45:52 dummyticketx1 2020-05-02 17:50:06 U
***DummyAsset66 2020-05-02 17:45:38 2020-05-02 17:45:52 dummyticketx1 2020-05-02 18:26:06 U***
DummyAsset66 2020-05-02 18:23:12 2020-05-02 18:23:59 dummyticketx2 2020-05-02 18:26:06 U
I don't want to print the second row alone but still need the 3rd row from the output, below Left Join is returning more than one row.我不想单独打印第二行,但仍然需要 output 的第三行,左连接下方返回多行。 I want to take the first row alone.
我想一个人坐第一排。
LEFT JOIN pmm.PmmLogChange AS PLC With (nolock) ON PRR.ManagedAccountID = PLC.ManagedAccountID and PRR.ExpiresDt < PLC.ChangeDt
If I get this correctly, you want to deduplicate your result set by certain set of columns (apparently by AssetName
and TicketNumber
).如果我理解正确,您希望通过某些列集(显然是
AssetName
和TicketNumber
)对结果集进行重复数据删除。 Since SQL Server lacks DISTINCT ON
operator, I suggest you use the following trick as described here由于 SQL 服务器缺少
DISTINCT ON
运算符,我建议您使用此处描述的以下技巧
You basically populate each row in your projection with row number like this ROW_NUMBER() OVER(PARTITION BY <whatever columns you consider as deduplication keys like AssetName,TicketNumber, ...>)
then filter out all rows with ROW_NUMBER() > 1
instead of using DISTINCT
operator.您基本上使用像这样的行号填充投影中的每一行
ROW_NUMBER() OVER(PARTITION BY <whatever columns you consider as deduplication keys like AssetName,TicketNumber, ...>)
然后过滤掉所有ROW_NUMBER() > 1
的行使用DISTINCT
运算符。 And btw, I agree with @marc_s, you shouldn't be using NOLOCK
like you do.顺便说一句,我同意@marc_s,你不应该像你一样使用
NOLOCK
。
But if the problem is only with last join you can replace it with subquery like this (SELECT TOP 1... FROM pmm.PmmLogChange AS PLC WHERE PRR.ManagedAccountID = PLC.ManagedAccountID AND PRR.ExpiresDt < PLC.ChangeDt ORDER BY PLC.ChangeDt ASC) AS mngac
但是,如果问题仅在于最后一个连接,您可以用这样的子查询替换它
(SELECT TOP 1... FROM pmm.PmmLogChange AS PLC WHERE PRR.ManagedAccountID = PLC.ManagedAccountID AND PRR.ExpiresDt < PLC.ChangeDt ORDER BY PLC.ChangeDt ASC) AS mngac
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.