全部评论
select a.name_id,a.order_country,ifnull(b.cnt,0) as order_counts from sell_information a left join (select name_id,order_country,count(order_id) cnt from sell_information group by name_id,order_country) b on a.name_id=b.name_id and a.order_country=b.order_country 首先就是查找每个用户每个国家的消费订单数,也就是得到表b(因为目前表b是不含订单为0的国家的),然后再让原表进行左连接,左连接的目的就是保留原有的国家,连接之后的新表就含有每个国家了,然后再用ifnull函数将这些没有订单数的国家的订单数量变成0.
SELECT c.name_id, c.order_county, IFNULL(d.count,0) AS count FROM ( SELECT a.id, a.name_id, b.order_county FROM (SELECT a.name_id, 1 AS id FROM zty_info AS a GROUP BY a.name_id) AS a LEFT JOIN ( SELECT b.order_county, 1 AS id FROM zty_info AS b GROUP BY b.order_county ) AS b ON a.id=b.id ) AS c LEFT JOIN ( SELECT e.name_id, e.order_county, COUNT(*) AS count FROM zty_info AS e GROUP BY e.name_id,e.order_county ) AS d ON c.name_id=d.name_id AND c.order_county=d.order_county 数据顺序自己最后重新排序就行
思路:t1 , t2 产生笛卡尔积得到每一个人对应每一个国家,然后把t3表左连接再配合IFNULL即可 SELECT t1.name_id , t2.order_county , IFNULL(num,0) AS order_counts FROM ( SELECT DISTINCT name_id FROM sell_information ) t1 JOIN ( SELECT DISTINCT order_county FROM sell_information ) t2 LEFT JOIN ( SELECT name_id , order_county , COUNT(order_id) AS 'num&(30597)#39; FROM sell_information GROUP BY name_id , order_county ) t3 ON t3.name_id = t1.name_id AND t3.order_county = t2.order_county ORDER BY name_id,order_county;
这是哪家的笔试
相关推荐
点赞 评论 收藏
分享