SQL查询 - 选择语句

时间:2011-09-30 14:22:46

标签: sql sql-server-2008 select

我有一张表格,数据可能如下所示:

  

CusID |名称|国家| PhyAddress

     

160285 | FYZPZ | NULL | 0

     

160285 | FYZPZ | NJ | 1

     

160285 | FYZPZ | NJ | 1

  

CusID |名称|国家| PhyAddress

     

160285 | FYZPZ | NJ xx | 1

  

CusID |名称|国家| PhyAddress

     

160285 | FYZPZ | NULL | 0

     

160285 | FYZPZ | NJ xx | 0

我需要获取用户的默认状态。逻辑是:

结果应首先显示physcial状态(PhyAddress = 1)和if 没有物理地址(PhyAddress = 0),那么它应该显示邮件地址状态(PhyAddress = 0)。如果没有,则状态可以为空。

表中有多个客户,每个客户都可以有多行,如上所述,我需要为每个客户获取默认状态。

结果需要显示CusID, Name, State

的结果

请帮我查询一下。 TIA

4 个答案:

答案 0 :(得分:1)

使用(评论后编辑):

SELECT DISTINCT Y.CusID, Y.Name, ISNULL (Y.S1, Y.S0) AS State
FROM
(
SELECT
X.CusID,
X.Name,
( SELECT MAX ( State ) FROM Address T WHERE T.PhyAddress = 1 AND T.CusID = X.CusID ) AS S1,
( SELECT MAX ( State ) FROM Address T WHERE T.PhyAddress = 0 AND T.CusID = X.CusID ) AS S0
FROM Address AS X
) AS Y

答案 1 :(得分:0)

搜索PhyAddress的最大值:

SELECT CusID, 
       State
FROM table t1
WHERE PhyAddress = 
    (
        SELECT MAX(t2.PhyAddress)
        FROM table t2
        WHERE t2.CusID = t1.CusID
    )

答案 2 :(得分:0)

你有什么尝试?

让我给你一些东西让你去

 Select CusID, Name, case when phyaddress = something then something
        when
        when
        ELSE ' ' END as State

from sometable

where something

答案 3 :(得分:0)

您可以执行类似

的操作
select CusID, Name, State, PhyAddress from sometable where (CusID, PhyAddress) in
  (select CusID, max(PhyAddress) from sometable)
  group by CusID, Name, State, PhyAddress