SQL 難點解決之集合及行號
可直接閱讀原文:http://c.raqsoft.com.cn/article/1542508403539?r=alice
1、 和集
示例 1:求重疊時間段的總天數
MySQL8:
with recursive t(start,end) as (select date'2010-01-07',date'2010-01-9'
union all select date'2010-01-15',date'2010-01-16'
union all select date'2010-01-07',date'2010-01-12'
union all select date'2010-01-08',date'2010-01-11'),
t1(d,end) as (select start,end from t
union all select d+1,end from t1 where d
select count(distinct d) from t1;
說明:此例先將各時間段轉成時間段內所有日子對應的日期,然後再求不同日期的個數
集算器SPL:
A | |
1 | =connect("mysql") |
2 | =A1.query("select CountryCode,Name,Language,Percentage from world.countrylanguage cl join world.country c on cl.countrycode=c.code where percentage>5") |
3 | =A2.group(CountryCode) |
4 | =A3.select(["English","French"]\~.(Language)==[]) |
5 | =A4.new(~.Name:name) |
A4: 選出[“English”,”French”]與本組語言集合的差為空的組,意思就是選出語言集合包含English和French的組
2、 差集
示例 1:列出英語人口和法語人口均超過 5% 的國家
MySQL8:
with t1(lang) as (select 'English' union all select 'French')
select name from world.country c
where not exists(select * from t1 where lang not in (select language from world.countrylanguage where percentage>=5 and countrycode=c.code));
說明:此SQL只是演示通過雙重否定實現差集為空
3、 交集
示例 1:列出英語人口、法語人口、西班牙語人口分別超過 0.3%、0.2%、0.1% 的國家程式碼
MySQL8:
with t1 as (select countrycode from world.countrylanguage where language='English' and percentage>0.3),
t2 as (select countrycode from world.countrylanguage where language='French' and percentage>0.2),
t3 as (select countrycode from world.countrylanguage where language='Spanish' and percentage>0.1)
select countrycode
from t1 join t2 using(countrycode) join t3 using(countrycode);
說明:此例只是演示如何求解多個集合的交集
集算器SPL:
A | |
1 | =connect("mysql") |
2 | [English,French,Spanish] |
3 | [0.3,0.2,0.1] |
4 | =A2.([email protected]("select countrycode from world.countrylanguage where language=? and percentage>?",~,A3(#))) |
5 | >A1.close() |
6 | =A4.isect() |
A3: 按次序依次查詢英語人口超0.3%、法語人口超0.2%、西班牙語超0.1%的國家程式碼,並轉成序列
A5: A3中所有序列交集
具體的行號可看原文實現方式:http://c.raqsoft.com.cn/article/1542508403539?r=alice
作者:zaoya
來源:乾學院
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。