简体   繁体   中英

Sub-query returning more than 1 row: SQL Server

Sub-query returning more than 1 row.

My current SQL Server query looks like this

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.

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. 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 ). Since SQL Server lacks DISTINCT ON operator, I suggest you use the following trick as described here

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. And btw, I agree with @marc_s, you shouldn't be using NOLOCK like you do.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM