相同的记录要在SQL中删除

时间:2018-12-03 14:03:51

标签: sql

我的表结构如下: 表格结构

Customer_Name   Month   Year    Effective_Date  Value
  Sanjay         Jan    2018      01-Jan-18       10
  Sanjay         Feb    2018      01-Feb-18       11
  Sanjay         Mar    2018      01-Mar-18       11
  Sanjay         Apr    2018      01-Apr-18       13
  Sanjay         May    2018      01-May-18       15
  Sanjay         Jun    2018      01-Jun-18       15
  Sanjay         Jul    2018      01-Jul-18       15
  Sanjay         Aug    2018      01-Aug-18       16
  Sanjay         Sep    2018      01-Sep-18       14

我想要这样的输出:

Customer_Name   Month   Year    Effective_Date  Value
  Sanjay         Jan    2018      01-Jan-18       10
  Sanjay         Feb    2018      01-Feb-18       11
  Sanjay         Apr    2018      01-Apr-18       13
  Sanjay         May    2018      01-May-18       15
  Sanjay         Aug    2018      01-Aug-18       16
  Sanjay         Sep    2018      01-Sep-18       14

逻辑:如果同时行的值相同,那么只会出现第一行。

我可以使用光标来做到这一点。但是我不想使用游标。还有其他方法吗?

4 个答案:

答案 0 :(得分:0)

检查两个脚本是否找到相同的结果:

SELECT   Customer_Name
        ,YEAR(MIN(Effective_date)) [Year]
        ,DATENAME(month,MIN(Effective_date)) [Month]
        ,MIN(Effective_date) Effective_date
        ,Value
FROM TableCustomer
GROUP BY Customer_Name
        ,Value



SELECT   T1.*
FROM TableCustomer T1
INNER JOIN (SELECT Customer_Name,Value,MIN(Effective_date) Effective_date FROM TableCustomer GROUP BY Customer_Name,Value) T2  
        ON T1.Customer_Name = T2.Customer_Name 
        AND T1.Value = T2.Value 
        AND T1.Effective_date = T2.Effective_date
ORDER BY T1.Effective_date

答案 1 :(得分:0)

您可以通过以下方式使用ROW_NUMBER()来实现:

select Customer_Name, Month, Year, Effective_Date, Value
from (
    select 
        *,
        cast(Effective_Date as date) as sort_date, 
        row_number() over(partition by Value order by cast(Effective_Date as date)) as rn
    from #t
)x
where rn = 1
order by sort_date

答案 2 :(得分:0)

如果Effective_DateDate数据类型:

SELECT * FROM tablename t 
WHERE 
t.Effective_Date = (
    SELECT MIN(tt.Effective_Date) FROM tablename tt 
    WHERE 
    tt.Customer_Name = t.Customer_Name AND
    tt.Month = t.Month AND
    tt.Year = t.Year AND
    tt.Value = t.Value
)

如果模式始终与上述示例相同,则可以省略:

tt.Month = t.Month AND
tt.Year = t.Year AND

答案 3 :(得分:0)

您可以按以下方式使用CTE,

WITH Customer_CTE(Effective_Date)
AS
(
    SELECT MIN(Effective_Date) AS Effective_Date
    FROM Customer
    GROUP BY Value
)

SELECT * FROM Customer WHERE Effective_Date IN (SELECT DISTINCT Effective_Date FROM Customer_CTE)