【问题标题】:Sorting data from one table based on another table根据另一个表对一个表中的数据进行排序
【发布时间】:2014-02-19 20:23:18
【问题描述】:

这是我的桌子:

create table tableA (id int, type varchar(5))
insert into tableA (ID,TYPE)
values

    (101,'A'),
    (101,'C'),
    (101,'D'),
    (102,'A'),
    (102,'B'),
    (103,'A'),
    (103,'C')

create table tableB (id int, type varchar(5), isActive bit)
insert into tableB (id, type, isActive)
Values 

    (101,'A',1),
    (101,'B',0),
    (101,'C',0),
    (101,'D',1),

    (102,'A',1),
    (102,'B',0),
    (102,'C',1),
    (102,'D',1),

    (103,'A',1),
    (103,'B',1),
    (103,'C',1),
    (103,'D',1)

现在,我想在这里做两件事: 1) 在tableA 中找到存在于isActive = 0 中但在tableB 中存在的行。 (完成)

select A.* from tableA A
join tableB B
on A.id = B.id and A.type = B.type 
where B.isactive = 0  

2) 查找tableA 中缺少但isActive = 1tableB 中缺少的行。 例如 ID 103,类型 B 在 tableB 中处于活动状态,但在表 A 中缺失。 我不关心 tableA 中 D 类型的存在,因为我只检查 tableA 中的最后一个条目,即 C。 此外,ABCD 是所有 ID 的顺序,它们可以是活动的或不活动的。

感谢您的帮助!

我的努力:(不工作)

select A.* from tableA A
where exists (
select B.* from tableA A
join tableB B 
on a.id = b.id 
where b.isActive = 1
order by b.id,b.type
)

SQLFiddle

【问题讨论】:

    标签: sql sql-server-2008 select sql-order-by


    【解决方案1】:

    我认为您正在寻找类似以下的内容:

    select B.* from tableB B
    left join tableA A
      on B.id = A.id and B.type = A.type
    where B.isActive = 1
      and A.id is null
    order by B.id, B.type
    

    通过使用左连接,这意味着 tableB 中没有行可与 tableA 连接的行将所有 A.* 列都为空。然后,这允许您添加 where 子句来检查 tableA 记录在哪里为空,从而确定 tableB 中包含的内容是活动的,而不是在 tableA 中

    【讨论】:

    • 我们真正期望的结果是来自 tableA 的 103 B,因为我们只想检查 tableA 直到该 ID 的最后一个类型。例如,对于 ID 101,最后一个类型是 D,所以我们应该在 tableB 中为 ID 101 检查活动 A、B、C、D。对于 ID 102,B 是最后一个类型,所以在 tableB 中我们只检查 A 和 B对于 102,如果 tableA 中缺少 B 中活动的行,则希望进入结果集。
    • 我不太清楚你在这里的意思。该查询将返回不在 TableA 中但在 TableB 中处于活动状态的值。
    猜你喜欢
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多