在查询中选择所有记录

时间:2012-06-29 03:23:12

标签: sql-server

我试过这个查询但没有运气:

SELECT tr.transferfrom, tr.transferto, br.id as 'BR_ID',
  tr.refno, br.name as 'BR_NAME', br.code as 'BRANCH_CODE',
  tr.docno, tr.transdate, stk.stockno,stk.salescat,tr.qty,
  tr.sprice,tr.qty*tr.sprice as 'GROSS_SALES' 
FROM TRANSFER tr 
JOIN branch br on tr.branchid=br.id 
JOIN stocks stk on tr.stockid=stk.id 
WHERE (tr.docno = 'ST00576' AND br.id IN ('*')) 
OR RIGHT(tr.refno,7) = 'ST00576' AND LEFT(tr.refno,3) IN ('*')

如果br.id是空值,我想查询选择所有记录。

1 个答案:

答案 0 :(得分:1)

有一个获得所有分支ID的子查询,然后IN查询可以引用子查询的输出..子查询将类似于select br.id from branch br

因此整个查询看起来像:

SELECT 
  tr.transferfrom, 
  tr.transferto, 
  br.id as 'BR_ID',
  tr.refno,
  br.name as 'BR_NAME', 
  br.code as 'BRANCH_CODE', 
  tr.docno,
  tr.transdate, 
  stk.stockno,
  stk.salescat,
  tr.qty,
  tr.sprice,
  tr.qty*tr.sprice as 'GROSS_SALES' 
FROM TRANSFER tr 
  JOIN branch br 
    on tr.branchid=br.id 
  JOIN stocks stk 
    on tr.stockid=stk.id
WHERE (
  tr.docno = 'ST00576' 
  AND br.id IN (select br.id from branch br)
  ) 
  OR RIGHT(tr.refno,7) = 'ST00576' 
  AND LEFT(tr.refno,3) IN ( select br.id from branch br)