2017-01-25 130 views
0

行我有以下幾點:刪除基於另一行

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 

該查詢有效,但我該如何更改它以便我不必指定庫存?我想保留與零客戶行是它是與該股票相關的唯一價值。

+0

不會這項工作'如果客戶是null'您問:'我如何改變它,這樣我就不必指定股票? ' – TheGameiswar

+0

對不起,我應該指定。我想保留空行的客戶是它是與該股票號碼相關聯的唯一價值 –

回答

5

可以使用存在:

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 
) 

這隻會刪除記錄凡客爲null,並且至少有一個記錄具有相同股票ID。

+0

你的邏輯是相反的,你正在刪除與客戶信息 –

+0

@ t-clausen.dk好行!只是錯誤地放在'不'.... ....固定。 –

0

只要做到delete from table where customer is null如果這是您唯一的要求。

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

請檢查下面的SQL DELETE CTE表達 內命令我使用SQL Count function with Partition By條款。 爲了測試NOT NULL客戶字段值我數了每隻股票與歸檔名使我能夠去除NULL

;with cte as (
    select 
     stock, 
     Customer, 
     cnt = Count(Customer) over (partition by stock) 
    from StockCustomer 
) 
delete from cte 
where Customer is null and cnt > 0 

你可以考慮像不同的情況在以下行

create table StockCustomer (stock int, Customer varchar(10)) 
insert into StockCustomer select 12345 , NULL 
insert into StockCustomer select 12345 , 'ABC' 
insert into StockCustomer select 11111 , 'XYZ' 
insert into StockCustomer select 555555 , NULL 
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