简体   繁体   English

SQL隐藏/显示基于其他表中行数的行

[英]SQL Hide/Show rows based on row count from another table

I have a SQL question. 我有一个SQL问题。 I have two tables, tableA has 4 records, tableB has 0 records right now, but will go over 200 total records. 我有两个表, tableA具有4条记录, tableB有0条记录的权利,但会超过200个总记录。 I was wondering if there is away to hide the last two records of tableA if tableB is under 200 records? 我想知道如果tableB在200条记录以下,是否可以隐藏tableA的最后两条记录?

What I got so far is very simple 到目前为止,我得到的非常简单

SELECT 
    id, dateSlot, timeSlot
FROM 
    tableA a 
INNER JOIN
    tableB b ON a.id = b.dateTimeSlotId;

I just don't know how to hide records based on another tables total records. 我只是不知道如何基于另一个表的总记录来隐藏记录。

Can anyone help? 有人可以帮忙吗?

It is only an idea. 这只是一个主意。 if the tables are not symmetric you need to improve the logic. 如果表不对称,则需要改进逻辑。

declare @tableA table (id int)
declare @tableB table (dateTimeSlotId int , dateSlot date, timeSlot time) 

insert @tableA values (1),(2),(3),(4),(5),(6),(7)
insert @tableB values 
(1,'20170801', '00:00'),
(2,'20170802', '00:01'),
(3,'20170803', '00:02'),
(4,'20170804', '00:03'),
(5,'20170805', '00:04'),
(6,'20170806', '00:05'),
(7,'20170807', '00:06')

;with cte as(
SELECT ROW_NUMBER() over (order by id) rNumber, id, dateSlot, timeSlot
FROM @tableA a INNER JOIN
     @tableB b
      ON a.id = b.dateTimeSlotId)
SELECT  id, dateSlot, timeSlot
FROM cte where rNumber <= (SELECT case when Count(1) >= 200 then Count(1) -2 else Count(1) end  from @tableB) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM