SQL server CROSS JOIN 的用法

SELECT @DateThreshold as dt,
		       t3.ck_id, t3.ck_name, t3.title_id,t3.title,
			   case when t4.num is null then 0 else t4.num end num,
			   case when t4.money is null then 0 else t4.money end money,
			   t3.startDay,t3.endDay  
		from 
		(SELECT t1.ck_id, t1.ck_name, t2.title_id,t2.title,t2.startDay,t2.endDay from
		(SELECT DISTINCT ck_id, ck_name FROM dws_erp_ku_ck_age_num_money_init WHERE dt = @DateThreshold) t1
		CROSS JOIN (SELECT DISTINCT id AS title_id ,title,startDay,endDay FROM dim_ku_kuAgeDateSet WHERE dt = @DateThreshold) t2
		) t3 
		left join (SELECT ck_id, ck_name, title_id, title, num, money 
				FROM dws_erp_ku_ck_age_num_money_init 
				WHERE dt = @DateThreshold) t4
		on t3.ck_id = t4.ck_id and t3.title_id = t4.title_id
		order by t3.ck_id

先将 两个表的维度进行 笛卡尔积 cross join,

SELECT t1.ck_id, t1.ck_name, t2.title_id,t2.title,t2.startDay,t2.endDay from
		(SELECT DISTINCT ck_id, ck_name FROM dws_erp_ku_ck_age_num_money_init WHERE dt = @DateThreshold) t1
		CROSS JOIN (SELECT DISTINCT id AS title_id ,title,startDay,endDay FROM dim_ku_kuAgeDateSet WHERE dt = @DateThreshold) t2

再和数据表进行left join 
最后补齐数据 缺失的数据补0 返回结果如下:

SQL server CROSS JOIN 的用法_第1张图片

你可能感兴趣的:(数据库,sql)