【问题标题】:Inserting multiple counts into a second mySQL table将多个计数插入第二个 mySQL 表
【发布时间】:2014-11-26 19:04:44
【问题描述】:

我一定看过一百多篇关于此的帖子,但没有一篇文章足够接近我可以弄清楚这一点。我有两张表——一张“住房”表和一张“汇总”表。我需要计算“房屋”表中的单元数, 1.) 具有“活跃”状态和“出租”类别,并且 2.) 具有“活跃”状态和“销售”类别 ...在几个建筑物中的每一个中,然后在“汇总”表中的建筑物名称旁边插入计数:

‘住房’表

Building                Unit No.    Status  Class     
----------             ----------    -------    ------
10 South Hampton            1107    Active  Rental
1 Nile Place                 712    Active  Sale
Forsythe Tower N            203N    Closed  Sale
Forsythe Tower S            117S    Active  Rental
Hickory Commons              315    Closed  Sale
10 South Hampton             202    Active  Sale
1 Nile Place                 311    Active  Rental
Forsythe Tower N            619N    Active  Rental
Forsythe Tower N            408N    Active  Sale
Hickory Commons             202     Closed  Sale
10 South Hampton            1420    Closed  Rental
1 Nile Place                 507    Active  Rental
Forsythe Tower N            810N    Active  Sale
Forsythe Tower S            716S    Active  Sale
Hickory Commons              319    Active  Rental

‘汇总’表

Building               Sales     Rentals    Col3    Col4    Col5
----------            ------     -------    ------  -----   ------
1 Nile Place               1      2
10 South Hampton           1      1
Forsythe Tower N           2      1
Forsythe Tower S           1      1
Hickory Commons            0      1

我得到了一个单一的计数(销售):

REPLACE summary (Building, Sales) 
SELECT   Building,
COUNT(*) FROM housing WHERE Status='Active' AND class ='Sales',
GROUP BY Building

然后我觉得很危险,发现下面的片段,看起来很棒,但对两者都不起作用

REPLACE summary (Sales, Rentals)
SELECT  Building,
        SUM(Class ='Sales' AND Status='Active') Sales,
        SUM(Class='Rentals' AND Status='Active') Rentals
FROM summary
GROUP BY Building

我真的只是在 mySQL 的这方面沾沾自喜,因此非常感谢有关如何破解它的建议。

谢谢。

【问题讨论】:

    标签: mysql replace insert count


    【解决方案1】:

    我没有在这里测试我的语法,但这是一般的想法:

    select Building,
    sum(case when Class='Sales' and Status='Active' then 1 else 0 end) Sales,
    sum(case when Class='Rentals' and Status='Active' then 1 else 0 end) Rentals
    from summary
    group by Building
    

    【讨论】:

      【解决方案2】:

      ALTER 表摘要 ADD Counts VARCHAR(60) AFTER Building;

      SELECT Count(DISTINCT Housing.Status)

      FROM 住房 h,摘要 s

      WHERE Status ='Active' AND (Class ='Sales' OR Class ='Rental')

      加入总结

      开启 s.Building = h.Building;

      【讨论】:

        猜你喜欢
        • 2015-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-13
        • 2010-12-07
        • 2016-10-19
        • 1970-01-01
        • 2014-05-15
        相关资源
        最近更新 更多