很抱歉,如果我没有正确解释这一点,我对SQL相对较新。
在oracle中有一个描述属性的表(城市,房产类型,每月租金,其他信息)
我的问题是:假设3种独特的房产类型(酒店,房屋,空地),我如何显示哪些城市没有所有3种类型的房产?
答案 0 :(得分:1)
GROUP BY
解决方案,确保每个城市返回的属性类型少于3种:
select city
from tablename
where property_type in ('hotel', 'house', 'empty lot')
group by city
having count(distinct property_type) < 3
答案 1 :(得分:1)
您的SQL查询应该是
SELECT City 来自YourTable 酒店&lt;&gt; 'hotelname'和house&lt;&gt; 'housename'和emptylot&lt;&gt; '名称'
假设 酒店,House,Emptylot是您数据库中的列名。
答案 2 :(得分:0)
(已修改)尝试此查询:
select t.city from table_name t
where t.city NOT IN
(select city from table_name
where ( property_type ='hotel' or
property_type ='house' or
property_type ='Empty lot')
);
(查询返回不存在所有三种属性的城市):
select t.city from table t inner join
(select city from table
where property_type not in ('House','Hotel','Empty lot')) x
on t.city=x.city
group by t.city
having count(*)<3 ;
答案 3 :(得分:0)
可能是这样的:
SELECT City
FROM YourTable
WHERE [property type] != 'hotel' OR
[property type] != 'empty lot' OR
[property type] != 'house'
答案 4 :(得分:0)
有两种方法,
GROUP BY
COUNT() OVER()
例如,假设我有3个城市的样本数据,其中城市1的所有属性类型都满意,其他城市则没有所有必需的属性类型。
使用GROUP BY
SQL> -- sample table data
SQL> WITH DATA AS(
2 SELECT 1 city, 'hotel' property FROM dual UNION ALL
3 SELECT 1 city, 'house' property FROM dual UNION ALL
4 SELECT 1 city, 'empty' property FROM dual UNION ALL
5 SELECT 2 city, 'hotel' property FROM dual UNION ALL
6 SELECT 2 city, 'house' property FROM dual UNION ALL
7 SELECT 2 city, 'scrap' property FROM dual UNION ALL
8 SELECT 3 city, 'empty' property FROM dual UNION ALL
9 select 3 city, 'house' property from dual
10 )
11 -- query
12 SELECT city
13 FROM data
14 WHERE property IN ('hotel', 'house', 'empty')
15 GROUP BY city
16 HAVING COUNT(property) < 3
17 /
CITY
----------
2
3
SQL>
使用分析COUNT()OVER()
SQL> -- sample table data
SQL> WITH DATA AS(
2 SELECT 1 city, 'hotel' property FROM dual UNION ALL
3 SELECT 1 city, 'house' property FROM dual UNION ALL
4 SELECT 1 city, 'empty' property FROM dual UNION ALL
5 SELECT 2 city, 'hotel' property FROM dual UNION ALL
6 SELECT 2 city, 'house' property FROM dual UNION ALL
7 SELECT 2 city, 'scrap' property FROM dual UNION ALL
8 SELECT 3 city, 'empty' property FROM dual UNION ALL
9 select 3 city, 'house' property from dual
10 )
11 -- query
12 SELECT DISTINCT city
13 FROM
14 (SELECT t.* ,
15 COUNT(property) OVER(PARTITION BY city ORDER BY city) rn
16 FROM DATA t
17 WHERE property IN ('hotel', 'house', 'empty')
18 )
19 WHERE rn < 3
20 /
CITY
----------
2
3
SQL>