我有桌子Address,Property并且Listing:
Create Table Listing
( PropertyID int -- Property ID as per the Property table
, AgentID int
, ListingDate DateTime not null property
, AskingPrice Decimal(10,2) not null
, SaleDate Date
, SalePrice Decimal(10, 2)
, Primary Key (PropertyID, ListingDate)
, Foreign Key (PropertyID) references Property(PropertyID)
, Foreign Key (AgentID) references Agent(AgentID) on delete no action on update no action
Create Table Address
( AddressID int Primary Key
, StreetAddress varchar (100)
, City varchar (50)
, StateCode char(3)
, PostalCode char (12)
, Country varchar(30)
)
)
Create Table Property
( PropertyID int Primary Key -- Unique ID for each property
, AddressID int references Address(AddressID) On Delete no action on update no action
, NumberOfRooms int not null Check (NumberOfRooms > 0) -- Number of rooms
)
Run Code Online (Sandbox Code Playgroud)
我想创建一个视图,其中包含每个城市的待售物业数量及其平均价格.物业是出售时AskingPrice,不是和SaleDate = null.问题是我无法得到每个城市的计数因为我得到错误
每个GROUP BY表达式必须至少包含一个不是外部引用的列
我该如何解决这个问题?
我的代码:
create view MarketStatistics as
select City = a.City,
Properties = (select count(PropertyID)from Listing l where l.AskingPrice is not Null and l.SaleDate is Null group by a.City),
AskingPrice = (select avg(AskingPrice)from Listing)
from Address a
join Property p on p.AddressID = a.AddressID
join Listing l on p.PropertyID = l.PropertyID
Run Code Online (Sandbox Code Playgroud)
您的查询可以更加简单,只需在不使用子查询的情况下进行分组:
select
a.City,
count(*) as Properties,
avg(l.AskingPrice) as AskingPrice
from Address a
inner join Property p on p.AddressID = a.AddressID
inner join Listing l on p.PropertyID = l.PropertyID
where l.AskingPrice is not Null and l.SaleDate is Null
group by a.City
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
227 次 |
| 最近记录: |