根据另一行删除一行

时间:2017-01-25 14:23:42

标签: sql-server sql-server-2008

我有以下内容:

stock   |   Customer   
12345   |   NULL
12345   |   ABC

我想要做的是在没有影响第二个的情况下删除第一个,只要有一组这样的行:

 if exists (select stock   from table WHERE stock='12345' AND Customer   is not null )
            BEGIN
                DELETE FROM table WHERE stock= '12345' AND  Customer    is null
            END

查询有效,但如何更改它以便我不必指定库存?我希望将行保留为null客户是它是与该股票相关联的唯一值。

5 个答案:

答案 0 :(得分:5)

您可以使用exists:

DELETE t0
FROM table t0
WHERE Customer IS NULL
AND EXISTS
(
    SELECT 1
    FROM table t1
    WHERE t0.stock = t1.stock
    AND t1.Customer IS NOT NULL
)

这只会删除客户为空的记录,并且至少有一条记录具有相同的库存ID。

答案 1 :(得分:3)

请检查CTE表达式中的以下SQL DELETE命令 我使用了SQL Count function with Partition By子句。 为了测试NOT NULL客户字段值,我计算了每个库存的文件名,使我能够删除NULL

.mouth{
  top: 268px;
  left: 273px;
  position: relative;
  
  width: 100px;
  height: 100px;
  background-color: red;
}

.mouth.animate {
  animation-name: talk;
  animation-duration: 0.75s;
  animation-iteration-count: 5;
}

@keyframes talk {
  0%, 100%{
    top: 268px;
    left: 273px;
  }

  50% {
    top: 308px;
    left: 273px;
  }
}

您可以考虑以下行中的不同情况

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mouth"></div>
<button id="getQuote">Get Quote</button>

答案 2 :(得分:2)

使用以下内容:

WITH CTE (stock, customer, DuplicateCount)
AS
(
SELECT stock, customer,
ROW_NUMBER() OVER(PARTITION BY Stock ORDER BY customer desc) AS DuplicateCount
FROM [Table]
)
DELETE
FROM CTE
WHERE DuplicateCount > 1 and customer is NULL
GO

答案 3 :(得分:1)

您可以按如下方式使用cross join

    DELETE
    FROM mytable
    WHERE stock IN (
            SELECT m2.stock
            FROM mytable m1
            CROSS JOIN mytable m2
            WHERE m1.customer IS NULL
            GROUP BY m2.stock
            HAVING count(m2.stock) > 1
            )
    AND customer is NULL

答案 4 :(得分:0)

如果这是您唯一的要求,请执行delete from table where customer is null