我有两张桌子
学校
CREATE TABLE Schools
(
BlockID INT,
SchoolID VARCHAR,
SchoolName VARCHAR,
powerAvail BIT,
waterAvail BIT
)
块
CREATE TABLE Blocks
(
BlockID INT,
BlockName VARCHAR
)
插入值:
Insert into Schools (1, 1, 'a', 0, 1)
Insert into Schools (2, 2, 'b', 1, 1)
Insert into Schools (2, 3, 'c', 0, 1)
Insert into Blocks (1, 'A')
Insert into Blocks (2, 'B')
现在我必须创建一个列出3列的视图:阻止名称,可用功率区块中的学校数量1,可用水区块中的学校数量1 按块名称分组结果。
注意:电源可用状况不应取决于可用水量。
答案 0 :(得分:1)
您可以在BlockID上加入学校和街区表格,然后在电量或水量为1时进行总和。
#app_root/config/initializers/constants.rb
HEROKU_ENV_USERNAME = ENV['HEROKU_ENV_USERNAME']
HEROKU_ENV_PASSWORD = ENV['HEROKU_ENV_PASSWORD']
结果:
SELECT
B.BlockName,
SUM(case when powerAvail=1 then 1 else 0 end) as 'Count_Schools_Power_Available',
SUM(case when waterAvail=1 then 1 else 0 end) as 'Count_Schools_Water_Available'
FROM
Schools S,
Blocks B
WHERE
S.BlockID = B.BlockID
GROUP BY
B.BlockName;
答案 1 :(得分:1)
你应该可以这样做:
SELECT B.BlockName,
SUM(CAST(powerAvail as int)) as num_powerAvail,
SUM(CAST(waterAvail as int)) as num_waterAvail
FROM Schools S JOIN
Blocks B
ON S.BlockID = B.BlockID
GROUP BY B.BlockName;