将多个计数插入第二个mySQL表

时间:2014-10-01 20:17:39

标签: mysql replace insert count

我一定已经看过这一百多个帖子,而且没有一个能够达到足够接近的地方,我可以解决这个问题。我有2个桌子 - 一个'住房'桌子和一个'总结'桌子。我需要计算'住房'表中的单位数量, 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

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

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的这个方面弄湿了所以如此破解这个建议将非常感激。

感谢。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

ALTER表摘要ADD Counts VARCHAR(60)建立之后;

SELECT Count(DISTINCT housing.Status)

FROM housing h,summary s

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

加入摘要

ON s.Building = h.Building;