如何为下表编写SQL查询?

时间:2014-06-17 11:06:38

标签: sql

我的表定义如下:

名称也是字符串和属性。

ID | Name | Property

此表中数据的示例如下:

ID | Name | Property
1    Peter  Newsletter
2    Paul   Register
3    Peter  Register
4    Shaun  Newsletter
5    Steve  Register

现在,我想查询所有拥有房产新闻通讯并注册的人。 因此,我应该得到彼得,因为他有两个属性。

因此得到的表应该是:

ID | Name | Property
1    Peter  Newsletter
3    Peter  Register

所以我试图询问的是哪个人都有财产的通讯和注册。

5 个答案:

答案 0 :(得分:5)

这是一种方法:

select t.*
from table t
where exists (select 1
              from table t2
              where t2.name = t.name and t2.property = 'NewsLetter'
             ) and
      exists (select 1
              from table t2
              where t2.name = t.name and t2.property = 'Register'
             );

如果您只想要名称列表,可能需要id s,我会这样做:

select t.name
from table t
where t2.property in ('NewsLetter', 'Register')
group by t.name
having count(distinct property) = 2;

如何获取id的列表取决于您的数据库,例如listagg()group_concat()string_agg()

答案 1 :(得分:2)

另一种选择,与Gordon的解决方案几乎相同,但没有使用EXISTS

select * from tablename
where name in (select name from tablename where property = 'Newsletter')
and name in (select name from tablename where property = 'Register')

答案 2 :(得分:1)

如果不了解更多数据,很难确定。鉴于您给我们的确切要求,这将给出您显示的结果:

WITH multprop (multName) AS (
   SELECT NAME FROM myTable
       WHERE Property IN('Newsletter','Register')
       GROUP BY NAME
       HAVING count(*)>1 )
select id, Name, Property
 from multprop inner join myTable
      on multName = Name

但是你的要求中的细微差别会使事情变得混乱。例如,是否除了您列出的两个以外的属性值?或者名称可以使用相同的属性多次显示?

编辑:添加的WHERE子句将CTE中的行限制为请求的特定Property值集。这来自评论中更详细的要求。

答案 3 :(得分:1)

还有一种方法:

SELECT * FROM T as T1
WHERE Property IN ('Newsletter','Register')
      AND EXISTS (SELECT * FROM T 
                      WHERE Name=T1.Name 
                            and Property IN ('Newsletter','Register')
                            and Property <> T1.Property
                 )

SQLFiddle demo

答案 4 :(得分:1)

另一个,记录

WITH cteHasBoth
 as (select Name
       from MyTable
       where Property in ('Newsletter', 'Register')
       group by Name
       having count(*) = 2)
 select ID, Name
  from MyTable
  where name in (select Name from cteHasBoth)

这只需要在表格中进行两次扫描。

相关问题