T-SQL识别第一时间值出现在列中

时间:2016-08-02 16:40:48

标签: sql-server tsql

我正在使用Excel 2013并使用ODBC连接连接到SQL Server

我有一张这样的表:

id    PhoneNumber    Caller
--------------------------------
1     915869850      John
2     912586985      Mary
3     963285874      John
4     915869850      Richard
5     965878965      James
6     925869753      Richard
8     963285874      James

我需要添加一个标识第一次调用电话号码的列,并在随后的时间忽略它...

像这样:

id    PhoneNumber    Caller    First Time
-----------------------------------------
1     915869850      John      1
2     912586985      Mary      1
3     963285874      John      1
4     915869850      Richard   0
5     965878965      James     1
6     925869753      Richard   1
8     963285874      James     0

是否可以这样做?

你能帮助我吗?

4 个答案:

答案 0 :(得分:2)

假设SQL Server 2005+,您可以使用ROW_NUMBER,然后使用CASE表达式:

WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY PhoneNumber ORDER BY id)
    FROM dbo.Phones
)
SELECT  id,
        PhoneNumber,
        [Caller],
        CASE WHEN RN = 1 THEN 1 ELSE 0 END [First Time]
FROM CTE;

答案 1 :(得分:1)

另一种解决方案:

WITH FirstCallList AS
(
SELECT 
    MIN([id]) AS FirstIdForNumber
FROM
    Calls
GROUP BY
    PhoneNumber
)
SELECT
    Calls.id
    ,Calls.PhoneNumber
    ,Calls.Caller
    ,CASE WHEN FirstCallList.FirstIdForNumber IS NULL THEN 0 ELSE 1 END AS FirstTime
FROM 
    Calls
    LEFT OUTER JOIN FirstCallList ON Calls.id = FirstCallList.FirstIdForNumber
ORDER BY
    Calls.id
;

答案 2 :(得分:0)

对此的经典方法是自连接或这样的标量子查询:

select id, PhoneNumber,
    case
        when id = (
            select min(p2.id) from <Phones> p2
            where p2.PhoneNumber = p.PhoneNumber
        ) then 1 else 0
    end as [First Time]
from <Phones> p

答案 3 :(得分:0)

使用ROW_NUMBER()窗口函数,如下所示:

SELECT *, CASE WHEN (ROW_NUMBER() OVER
    (PARTITION BY PhoneNumber ORDER BY id))=1 THEN 1 ELSE 0 END FirstTime
FROM Src
ORDER BY id