简体   繁体   中英

Convert rows into columns in sub-query

I'm trying to convert rows into columns when using this in a subquery query like:

select distinct 
    bqtID, bqtName, bqtCity, bqtStatus, bqtManagerName,
    (select 
         max(case when serName = 'Capacity' then serStatus end) Capacity,
         max(case when serName = 'Parking' then serStatus end) Parking
     from 
         tblService 
     where 
         serBqtID = bqtID),
from 
    View_BanquetList 
where 
    bqtID = 1

I get this error:

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

While when I used it separately then it works:

select 
     max(case when serName = 'Capacity' then serStatus end) Capacity,
     max(case when serName = 'Parking' then serStatus end) Parking
from 
    tblService 
where 
    serBqtID = 1

Results:

Capacity    Parking
--------    -------
101-200     51-100

Why is it not converting multiple rows into columns in sub-query?

You are trying to return two columns as one in the select list. That doesn't work. I'm not an expert on SQL Server, but with Oracle there would be at least three options.

  1. Move the subselect to a with-clause and then join with it.
  2. Use two sub-selects, one for capacity and one for parking.
  3. Move the sub-select to the from clause and use a subselect that becomes a table, which is then joined.

I think all should work with SQL Server as well. Option 3 is closest to what you have now.

EDIT: try this:

select distinct 
    v.bqtID, v.bqtName, v.bqtCity, v.bqtStatus, v.bqtManagerName,
    t.Capacity, t.Parking
from 
    (select 
         serBqtID,
         max(case when serName = 'Capacity' then serStatus end) Capacity,
         max(case when serName = 'Parking' then serStatus end) Parking
     from 
         tblService
     group by 
         serBqtID) t 
inner join
    View_BanquetList v on t.serBqtID = v.bqtID
where 
    v.bqtID = 1

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