其他分享
首页 > 其他分享> > left join 和 group by 一起使用

left join 和 group by 一起使用

作者:互联网

--1 s 连接 s2 ,如果s表要写group by 就得用括号,因为s left join s2 是一张表只能有一个group by ,所以括号抱起来
SELECT s.coun1,s2.coun2
FROM
(SELECT ssex,count() coun1 FROM student group by ssex)s
LEFT JOIN
(select ssex,count(
) coun2 from student where sname='赵雷' group by ssex) s2
on s.ssex=s2.ssex

--2 大的表a里面包了:s left join s2 ,s后面不能写group by ,这样s 就是一个完整的sql,无法进行left join了
SELECT coun1,coun2 FROM
(
select s.ssex,count() coun1,s2.coun2 FROM student s
LEFT JOIN (select ssex,count(
) coun2 from student where sname='赵雷' group by ssex) s2
on s.ssex=s2.ssex
where 1=1
group by s.ssex,s2.coun2
) a

-- sql参考
SELECT
t.cllx,
nvl( t.sumCount, 0 ) sumCount,
nvl( t1.twentyFourCount, 0 ) twentyFourCount,
nvl( t2.fortyEightCount, 0 ) fortyEightCount,
nvl( t3.seventyTwoCount, 0 ) seventyTwoCount,
nvl( t4.sevenDay, 0 ) sevenDay,
nvl( t5.yangCount, 0 ) yangCount
FROM
( SELECT cllx, count( * ) sumCount FROM T_SUP_TC_NETCAR_HS t GROUP BY cllx ) t
LEFT JOIN (
SELECT
cllx,
count( * ) twentyFourCount
FROM
T_SUP_TC_NETCAR_HS t
WHERE
to_date( t.HSRQ, 'yyyy-MM-dd hh24:mi:ss' ) > ( SYSTIMESTAMP - 1 )
GROUP BY
cllx
) t1 ON t.cllx = t1.CLLX
LEFT JOIN (
SELECT
cllx,
count( * ) fortyEightCount
FROM
T_SUP_TC_NETCAR_HS t
WHERE
to_date( t.HSRQ, 'yyyy-MM-dd hh24:mi:ss' ) > ( SYSTIMESTAMP - 2 )
GROUP BY
cllx
) t2 ON t.cllx = t2.CLLX
LEFT JOIN (
SELECT
cllx,
count( * ) seventyTwoCount
FROM
T_SUP_TC_NETCAR_HS t
WHERE
to_date( t.HSRQ, 'yyyy-MM-dd hh24:mi:ss' ) > ( SYSTIMESTAMP - 3 )
GROUP BY
cllx
) t3 ON t.cllx = t3.CLLX
LEFT JOIN (
SELECT
cllx,
count( * ) sevenDay
FROM
T_SUP_TC_NETCAR_HS t
WHERE
to_date( t.HSRQ, 'yyyy-MM-dd hh24:mi:ss' ) > ( SYSTIMESTAMP - 7 )
GROUP BY
cllx
) t4 ON t.cllx = t4.CLLX
LEFT JOIN ( SELECT cllx, count( * ) yangCount FROM T_SUP_TC_NETCAR_HS t WHERE t.hsjg like '%阳%' GROUP BY cllx ) t5 ON t.cllx = t5.CLLX

标签:count,join,s2,ssex,cllx,group,SELECT,left
来源: https://www.cnblogs.com/chwl-ljx/p/16381623.html