在SQL Server中将函数()设置为1或0

时间:2015-03-05 19:55:10

标签: sql-server tsql rank

我需要帮助找到在SQL Server中执行以下操作的方法。

基本上,在Excel中,我可以编写如下内容:

IF(COUNTIF(A:A:A2) > 1:1:0))

此Excel代码的作用是,如果IT在客户编号列中找到重复的客户编号,则公式将返回1,否则为0.

我在我的代码中包含了这个

Select
    Contract_nr,
    Customer_number,
    Rank()OVER(ORDER BY customer_number) AS tester
    Productname,
    Sales_date
From 
    table namn

rank()返回1100,1105,依此类推......

如果客户编号重复,我如何制作IT以便我的测试人员列返回1或0?

3 个答案:

答案 0 :(得分:2)

with cte as (
Select
    Contract_nr,
    Customer_number,
    case
       when count(*) over (partition by Customer_number) > 1 then 1
       else 0
    end as tester
    Productname,
    Sales_date
From 
    table namn

答案 1 :(得分:1)

我会自我加入。如果您是SQL Server 2012或更高版本,则Lead和Lag是一个不错的选择。但这应该很好。

SELECT DISTINCT 
        Contract_nr,
        Customer_number,
        CASE WHEN t2.Contract_nr IS NOT NULL THEN 1 ELSE 0 END AS [CustomerNumIsRepeat],
        Productname,
        Sales_date
    FROM table as t1
    LEFT JOIN table as t2 ON t1.Customer_number = t2.Customer_Number AND t1.Contract_nr != t2.Contract_nr

答案 2 :(得分:1)

我会使用WITH子句来获取每个客户编号的不同计数,如下所示:

; With CustomerNumberCount AS
(
    SELECT Customer_number, COUNT(*) AS RecordCount
    FROM table
    GROUP BY Customer_number
)
SELECT t1.*
    , CASE WHEN t2.RecordCount > 1 THEN 1 ELSE 0 END AS [CustomerNumIsRepeat]
FROM table as t1
    LEFT JOIN CustomerNumberCount as t2 ON t1.Customer_number = t2.Customer_Number

这将确保您只从t1获得1行(如果客户编号出现2次或更多次,可能会多次获得同一行)。