从两个表sql中选择字段

时间:2014-04-23 15:43:55

标签: sql tsql select

我有以下查询从数据库中选择记录。

目前工作正常。

select Barcode,systemqty from items where barcode in 
(select itibar from itrans group by itibar having sum(itiqty) <> systemqty) 
 and  brand='BRO'

现在,我需要从 itrans 表中选择另一个字段,如此

 select Barcode,systemqty,itibar from items where barcode in 
(select itibar from itrans group by itibar having sum(itiqty) <> systemqty) 
 and  brand='BRO'

上述代码会导致错误。

1 个答案:

答案 0 :(得分:0)

在您的示例中,如条形码= itibar,您可以只包含条形码

select Barcode,
        systemqty, 
        barcode as itibar 
from items 
where barcode in 
(
select itibar 
from itrans 
group by itibar 
having sum(itiqty) <> systemqty

) 
and  brand='BRO'

或者,您可以将其更改为联接,以允许您在select语句中从itrans访问更多列:

select Barcode,
        systemqty, 
        itibarrows.itibar 
from items 
inner join (
    select itibar 
    from itrans 
    group by itibar 
    having sum(itiqty) <> systemqty
    ) itibarrows
    on itibarrows.itibar = items.barcode
where brand='BRO'