简体   繁体   中英

Select Inner Join Select in SQL

Hi i Have a Select Inner Join Statement it seems ok but i got error. this is my query

ALTER PROCEDURE [dbo].[POBalance]  @PONumber nvarchar(50)
AS BEGIN
Select( 
Select 
    A.Description,
    C.qty as POqty,
    B.QtyDelivered as PDQty, 
    case when A.partialflag ='false' 
    then '0'
    else
    A.qty  end as Balance,
    A.Unit,
    A.Unitprice,
    A.Partialflag 
from tblPOdetails as A

Inner Join  ( SELECT  id, SUM(Qty) AS QtyDelivered
                                    FROM         dbo.tblPDdetails
                                    WHERE     (PONo = @PONumber)
                                    GROUP BY id)as B On A.id = B.id   
Inner Join tblpodetailshistory as C on A.id =C.id

where A.PONo = @PONumber)
END

I got this Error.

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

Thank you in Advance.

You should include the column names and From keyword in the outer select statement

ALTER PROCEDURE [dbo].[POBalance]  @PONumber nvarchar(50)
AS BEGIN
Select Description, POqty, PDQty, Balance, Unit, Unitprice, Partialflag  from ( 
Select 
    A.Description,
    C.qty as POqty,
    B.QtyDelivered as PDQty, 
    case when A.partialflag ='false' 
    then '0'
    else
    A.qty  end as Balance,
    A.Unit,
    A.Unitprice,
    A.Partialflag 
from tblPOdetails as A

Inner Join  ( SELECT  id, SUM(Qty) AS QtyDelivered
                                    FROM         dbo.tblPDdetails
                                    WHERE     (PONo = @PONumber)
                                    GROUP BY id)as B On A.id = B.id   
Inner Join tblpodetailshistory as C on A.id =C.id

where A.PONo = @PONumber)
END

Actually you don't need to write the outer select, it can be rewritten as

ALTER PROCEDURE [dbo].[POBalance]  @PONumber nvarchar(50)
AS BEGIN

Select 
    A.Description,
    C.qty as POqty,
    B.QtyDelivered as PDQty, 
    case when A.partialflag ='false' 
    then '0'
    else
    A.qty  end as Balance,
    A.Unit,
    A.Unitprice,
    A.Partialflag 
from tblPOdetails as A

Inner Join  ( SELECT  id, SUM(Qty) AS QtyDelivered
                                    FROM         dbo.tblPDdetails
                                    WHERE     (PONo = @PONumber)
                                    GROUP BY id)as B On A.id = B.id   
Inner Join tblpodetailshistory as C on A.id =C.id

where A.PONo = @PONumber
END

The issue is at the beginning of your query,

Select( Select ....

Remove the initial "Select (" and retry the query. When you run a

Select (Select ..) 

the second select can only return one column (unless you concatenate the returned data).

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