如何在where子句中使用max?

时间:2019-03-25 22:54:59

标签: sql sql-server

在我们的数据库中,每个客户最多可以有3个电话号码,每个电话号码都与一个ID_phone_number和一个ID_type_phone和id_person相关。

因此,我需要进行常规选择,它返回ID_type_phone ='2'并且具有与此ID_person相关的更高ID_phone_number的电话号码。

此选择需要对我的整个数据库有效,因此我无法在其上指定id_person

我有:

SELECT 
  (SELECT collun1.phone WHERE collun1.ID_type_phone = '2')
FROM collun1
WHERE id_person = 4

我想要类似的东西

SELECT 
  (SELECT collun1.phone WHERE collun1.ID_type_phone = '2' and max(id_phone_number)
FROM collun1

4 个答案:

答案 0 :(得分:1)

您可以将SQL Server的Rank函数与PARTITION和ORDER BY一起使用

类似

Select * from (
    Select  RANK() OVER (
        PARTITION BY id_person 
        ORDER BY id_phone_number desc) AS phoneRank
        ,*
    from    collun1
    WHERE   collun1.ID_type_phone = '2') as tempSub
where phoneRank = 1

答案 1 :(得分:0)

使用以下语法:

SELECT id_person, phone 
FROM collun1 
WHERE ID_type_phone = '2' AND id_phone_number = (SELECT MAX(id_phone_number) FROM collun1 c WHERE c.id_person = collun1.id_person)

答案 2 :(得分:0)

GROUP BY可能会更快(取决于您的数据):

SELECT id_person, MAX(ID_phone_number) 
FROM collun1 
WHERE ID_type_phone = '2' 
GROUP BY id_person

答案 3 :(得分:0)

所以我是通过根据Hadi答案创建一个临时表来实现的。

我做到了:`

CREATE TABLE ##Celphone (
Num_Phone varchar(14),
ID_Person numeric(8)); 

insert into ##Celphone (Num_Phone, ID_Person)
        SELECT Phone, ID_Person
        FROM COLLUN1 
        WHERE ID_Type_Phone = '2' AND ID_Phone = (SELECT MAX(ID_Phone) FROM COLLUN1 C WHERE C.ID_Person = COLLUN1.ID_Person)

SELECT DISTINCT
       ##Celphone.Num_Phone,
       ID_Person