如果存在一个值,则删除另一个值

时间:2015-10-22 08:30:54

标签: sql-server sql-server-2012 group-by remove-if

如果另一个帖子存在,我就陷入了关于如何删除或者跳过帖子的问题。

enter image description here

这是我的桌子。

如果 L_ID 列的值 821 201 P_ID ,则“删除”或“不要” t使用201和sum()然后时间

这会使P_ID 80和946只有2行。

这可能比我想象的要容易,但是我被卡住了。

2 个答案:

答案 0 :(得分:1)

试试这样:

CREATE TABLE #YourTable(P_ID INT, L_ID INT, [Date] Date, [Time] DECIMAL(6,2));
INSERT INTO #YourTable VALUES
 (80,201,{d'2015-08-01'},24.0)
,(80,821,{d'2015-08-01'},24.0)
,(80,822,{d'2015-08-01'},32.0)
,(946,201,{d'2015-08-01'},16.0)
,(946,821,{d'2015-08-01'},16.0)
,(946,819,{d'2015-08-01'},6.65)
,(6758,201,{d'2015-08-01'},7.25)
,(6758,200,{d'2015-08-01'},7.25)
;

--Test output
SELECT * FROM #YourTable;

--Set the SUMs in those lines with L_ID=821
UPDATE #YourTable SET [Time]=(SELECT SUM(x.[Time]) 
                              FROM #YourTable AS x 
                              WHERE x.P_ID =#YourTable.[P_ID] 
                                    AND x.L_ID IN (821,201))
WHERE #YourTable.L_ID=821

--Delete the rows with L_ID=201 if there is one with 821 too
DELETE FROM #YourTable 
WHERE L_ID = 201 AND EXISTS(SELECT * FROM #YourTable AS x 
                            WHERE x.P_ID = #YourTable.P_ID AND x.L_ID =821 ) --The ID was wrong here, sorry...

--Test output
SELECT * FROM #YourTable;

--Clean up
DROP TABLE #YourTable;

结果:

P_ID    L_ID    Date        Time
80      821    2015-08-01   48.00
80      822    2015-08-01   32.00
946     821    2015-08-01   32.00
946     819    2015-08-01   6.65
6758    201    2015-08-01   7.25
6758    200    2015-08-01   7.25

答案 1 :(得分:0)

试试这段代码:

SELECT *,
   SUM(Time) OVER(PARTITION BY P_ID, L_ID, Date) AS 'Sum'
FROM Your_Table
WHERE L_ID <> 201
   AND P_ID NOT IN (
      SELECT E1.P_ID
      FROM Your_Table E1
         INNER JOIN Your_Table E2
            ON E1.P_ID = E2.P_ID
      WHERE E1.L_ID = 821 AND E2.L_ID = 201)