【问题标题】:Need help in sql query to give result set based on previous version在 sql 查询中需要帮助以提供基于以前版本的结果集
【发布时间】:2014-01-27 08:24:38
【问题描述】:

我有两个表,table1 和 table2。

表格1 id 名称 城市 uqid 1 维卡斯迈索尔 2 表2 id uqid 名称 状态 1 1 维卡待定 1 2 Vikas 加工

我有一个 SQL 查询来获取与 table2 连接的 table1 的详细信息

select table1.id,
       table1.name,
       table1.city,
       table2.status
from table1 
   left outer join table2 
     on table2.uqid = table1.uqid 
    and table2.id = table1.id

这会给我结果集

id 名称 城市状态 1 vikas mysore 加工

如何修改上述查询,直到 uqid = 1 和 id = 1 的 table2 中的状态设置为“通过”之前不给我们结果集?

【问题讨论】:

  • 请任何人编辑问题以表格格式显示数据
  • 你想做什么? uqid = 1,id = 1 和 uniq = 2, id= 1 是什么关系?
  • 如果table2之前的所有状态都处于通过状态,我想获取table2中所有处于处理状态的id的结果集
  • 那么如何找出哪条记录是以前的呢?我的意思是如果 uqid 为 1 则前一个状态和 2 当前状态?
  • table1.uqid 与 table2.uqid 匹配的值始终是当前状态。 table2 中存在的该 id 且小于 uqid 的任何其他记录都被视为以前的

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2


【解决方案1】:

试试下面的。

select table1.id,
       table1.name,
       table1.city,
       table2.status
from table1 
   left outer join table2 
     on table2.uqid = table1.uqid 
    and table2.id = table1.id
where table2.status ilike 'pass';

如果说您需要 table2 的 uqid=id=1,则意味着您需要两个字段具有相同的值,然后使用以下内容。

select table1.id,
       table1.name,
       table1.city,
       table2.status
from table1 
   left outer join table2 
     on table2.uqid = table1.uqid 
    and table2.id = table1.id
where table2.status ilike 'pass' and table2.uqid=table2.id;

建议:尝试规范化您的表格

【讨论】:

  • 在代码块中添加查询,否则难以阅读。
  • 在你做的时候就在中间。无论如何,下次会照顾它
【解决方案2】:

我不确定这是正确的方法或是否存在任何其他有效的方法,但这会给你想要的结果。

select table1.id,
   table1.name,
   table1.city,
   table2.status
from table1 
left outer join table2 
on table2.uqid = table1.uqid and table2.id = table1.id
where table1.id in(select distinct id from table2 where status like 'pass' 
                   and uqid not in(select uqid from table1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    相关资源
    最近更新 更多