在显示条件下使用SELECT

时间:2015-08-18 17:24:38

标签: sql-server-2005

SELECT DISTINCT Invoice.InvNo, Invoice.OrderNo, Part.PartNo,
  orders.orddate AS Order_Date, Invoice.InvDate AS Bill_Date,
  MiscChg.Descr, MiscChg.RegFee, Invoice.InvAmt, 
  Orders.ClaimNo, Firm.FirmName AS Ordering_Firm, 
**oppatty.attyid(WHERE oppatty.attyfor = 13)**, Location.Name1 AS Location

粗体部分是我遇到麻烦的部分。我知道我所拥有的是不对的,但它证明了我想要完成的事情。在oppatty表中,可能会列出几个项目。我希望它只显示“具有ATTYFOR = 13的条目的AttyID”。

希望这有意义,谢谢

杰克

2 个答案:

答案 0 :(得分:0)

你的查询没有from或where子句,你的问题有点混乱,但即便如此,我想我明白你想做什么。假设使用null填充“AttyID”值是可以接受的,其中“AttyFor”不等于13,那么您可以使用case语句。试试这样的事情

select
    stuff.things,
    case 
        where oppatty.attyfor <> 13 then null
        else oppatty.attyid
    end as attyid,
    stuff.others
from
    oppatty
    join stuff on oppatty.ID = stuff.ID

如果这不是您想要的结果,而您宁愿完全排除“AttyFor”不等于13的行,那么只需使用where子句。

select
    stuff.things,
    oppatty.attyid,
    stuff.others
from
    oppatty
    join stuff on oppatty.ID = stuff.ID
where
    oppatty.attyfor = 13

答案 1 :(得分:0)

您需要在select语句中添加CASE WHEN

SELECT DISTINCT 
    Invoice.InvNo, 
    Invoice.OrderNo, 
    Part.PartNo, 
    orders.orddate AS Order_Date, 
    Invoice.InvDate AS Bill_Date, 
    MiscChg.Descr, 
    MiscChg.RegFee, 
    Invoice.InvAmt, 
    Orders.ClaimNo, 
    Firm.FirmName AS Ordering_Firm, 
    CASE WHEN oppatty.AttyFor = 13
         THEN oppatty.AttyId
         ELSE '' END AS attyfor, 
    Location.Name1 AS Location
FROM
    .........

当行AttyId字段等于13时,这将显示AttyFor字段,如果不是,则显示空字符串。