什么SQL查询会给我出售房屋的百分比(%)?

时间:2011-01-24 17:47:43

标签: sql-server

什么SQL查询会给出房屋销售价格的百分比(%),而不是每个房屋的价格:

“区域”,“构建类型”和“月份”?

表格是

{ Mls No, Build Type, Area code, List price, Sold price, Sold data }

但我只需要:

percentage (%) of houses  "sold price " over List price for each:
    "Area code ", "Build type" and "Month"

MLS No.   Area  List Price  Contract    Price Sold  Date Sold   Building Type
N1959472  N11   329500      20/09/2010  317000      13/11/2010  Semi-Detac 
N1990464  N11   339000      08/11/2010  340000      17/11/2010  Apt

3 个答案:

答案 0 :(得分:4)

您可以group by“每”字段,并使用聚合计算百分比,例如:

select  Area
,       Buildtype
,       Month
,       100.0 * sum(case when SoldPrice > ListPrice then 1 else 0 end) / count(*)
from    YourTable
group by
        Area
,       Buildtype
,       Month

如果没有Month列,但只有日期列,请将month替换为:

SQL Server:      datepart(month, SoldDate)
Oracle/MySQL:    extract(month from SoldDate)

答案 1 :(得分:1)

您不需要JOIN或UNION,只需将CASE放入查询中,如下所示:

select Area
     , Build_type
     , extract(month from sold_date) as month
     , SUM(case when sold_price > list_price then 1.0 else 0 end)
      /count(*) as pct_sold
  FROM theTable
 GROUP BY Area
        , build_type
        , extract(month from sold_date)

答案 2 :(得分:0)

没有列Month。您不需要joinunion,google用于GROUP BY