如何以这种方式选择数据库--sql

时间:2013-09-23 18:48:32

标签: sql sql-server database relational-division

我有这张桌子

id   owner   group     model  
1    1       shapes    circle  
2    1       shapes    rectangle  
3    1       shapes    squire  
4    2       fruits    apple  
5    2       fruits    orange  
6    2       fruits    banana  
7    3       shapes    circle  
8    3       shapes    rectangle  
9    3       shapes    star

每个所有者选择一个组并输入3个选项,现在我想找到选择形状并输入圆圈和星形的所有者。

必须返回所有者id = 3

3 个答案:

答案 0 :(得分:1)

假设groupmodel对于每个owner

都是唯一的
SELECT  a.owner
FROM    tableName a
WHERE   a.[group] = 'shapes' AND
        a.model IN ('circle','star')
GROUP   BY a.owner
HAVING  COUNT(*) = 2

否则,您需要唯一计算model

的数量
SELECT  a.owner
FROM    tableName a
WHERE   a.[group] = 'shapes' AND
        a.model IN ('circle','star')
GROUP   BY a.owner
HAVING  COUNT(DISTINCT a.model) = 2

答案 1 :(得分:1)

试试这个解决方案:

SELECT  *
FROM
(
SELECT owner, model
FROM dbo.MyTable
WHERE [group] = 'shapes' AND model IN ('circle', 'star')
) x
PIVOT( COUNT(x.model) FOR x.model IN ([circle], [star]) ) y
WHERE y.[circle] > 0 
AND y.[star] > 0

答案 2 :(得分:0)

在指定的参数范围内,这将起作用:     SELECT所有者WHERE [group] ='形状'AND model ='circle'     相交     SELECT owner WHERE [group] ='shapes'AND model ='star'