我有4个字段,如:
Country, Year, Area,Value
USA , 2010, SQL, 78
USA, 2011, C++, 66
UK, 2012, C, 99
现在在此表中
结果还应包含:
USA, 2012, C , 0
UK, 2010, SQL, 0
UK, 2012, C++, 0
就像按国家/地区和缺失区域(根据表中的条目),年份(根据表中的条目)循环并需要填写“0”。在sql函数/ query / triggers / anything。
我试过这样:
SELECT countryID, COUNT ("chart_data"."countryID") AS count
FROM tablename GROUP BY "countryID", "yearID"...
这可能吗?
答案 0 :(得分:3)
这是Postgresql或MySQL的答案,但它也适用于其他DBMS:
INSERT INTO tbl (Country, Year, Area, Value)
SELECT Countries.Country, Years.Year, Areas.Area, 0 As Value
FROM
(SELECT DISTINCT Country FROM tbl) Countries CROSS JOIN
(SELECT DISTINCT Year FROM tbl) Years CROSS JOIN
(SELECT DISTINCT Area FROM tbl) Areas
LEFT JOIN tbl ON tbl.Country=Countries.Country
AND tbl.Year=Years.Year
AND tbl.Area=Areas.Area
WHERE
tbl.Value IS NULL -- if it can't be null, otherwise choose any other field
请参阅小提琴here。