如何删除记录组

时间:2018-09-27 11:35:59

标签: sql sql-server

我在查询时遇到了麻烦,我不知道如何继续进行

表结构

create table event(
  evn_id int identity(1,1),
  name varchar(90)
)

create table eventdate(
  evd_id int identity(1,1),
  evd_evn_id int references event(evn_id),
  evd_start smalldatetime,
  evd_end smalldatetime null,
  evd_picked bit,
)

测试数据

Insert into eventdate
VALUES('1','1','2018-08-28 09:00:00','NULL','1'),
    ('1','2','2018-04-26 09:00:00','NULL','0'),
    ('1','3','2018-02-25 09:00:00','NULL','0'), 
    ('2','4','2018-03-26 15:00:00','NULL','1'),
    ('2','5','2018-04-25 09:00:00','NULL','0')

Insert into event
VALUES('1','test'),
('2','test')

每个事件可以有1个或多个事件日期,而一个事件日期有1个事件

我提供了以下内容,其中列出了1个或0个选择日期的事件日期

SELECT * 
FROM eventdate
WHERE evd_evn_id IN(
    SELECT evd_evn_id
    FROM eventdate
    GROUP BY evd_evn_id
    HAVING COUNT(CASE WHEN evd_picked = 1 then 1 else null end) <= 1)
ORDER BY evd_evn_id

我现在想做的是,如果evd_evn_id删除每个evd_evn_id的所有记录 有一个日期是在之前创建的选择日期(evd_picked = 1)  例如“ 20180613”

它应该返回的是

'2','4','2018-03-26 15:00:00','NULL','1'
'2','5','2018-04-25 09:00:00','NULL','0'

2 个答案:

答案 0 :(得分:0)

您可以在此要求中使用Output Clause with DELETE命令 引用文档中确实有一个类似的示例。

这是我可以为您建议的SQL脚本

declare @EventID table
(
  evn_id int
)

DELETE FROM eventdate
OUTPUT DELETED.evd_evn_id
INTO @EventID(evn_id)
WHERE evd_picked  = 1 and
      evd_start < '20180613'


DELETE FROM event
where evn_id in (select evn_id from @EventID)

答案 1 :(得分:0)

因此,如果我理解您的问题,那么,如果已选择了任何事件日期且开始日期在“ 20180613”之前,则希望从事件日期表中获得该事件的所有记录。

我从您期望的结果中假设了这一点。我将使用以下内容:

SELECT * 
FROM eventdate
WHERE evd_id in(
select evd_id from eventdate    WHERE evd_start < '2018-06-13' and evd_picked = 1)

删除:

DELETE FROM  eventdate
WHERE evd_id in(
select evd_id from eventdate    WHERE evd_start < '2018-06-13' and evd_picked = 1)