|
楼主 |
发表于 2020-4-14 18:30
|
显示全部楼层
自己写了一个费劲的SQL,麻烦看看能不能精简呀,谢谢。
查询汇总:
SELECT ABC.字段2,AA.查询A_NUM,BB.查询B_NUM,CC.查询C1_NUM,CC.查询C2_NUM,CC.查询C3_NUM,DD.查询D_NUM FROM
((((SELECT 字段2 FROM A WHERE 查询="Y" AND 状态="Y"
UNION SELECT 字段2 FROM B WHERE 查询="Y" AND 状态="Y"
UNION SELECT 字段2 FROM C WHERE (查询1="Y" OR 查询2="Y" OR 查询3="Y") AND 状态="Y"
UNION SELECT 字段2 FROM D WHERE 查询="Y" AND 状态="Y") ABC
LEFT JOIN (SELECT 字段2, COUNT(CASE WHEN 查询= 'Y' THEN 1 ELSE NULL END) AS 查询A_NUM FROM A WHERE 查询="Y" AND 状态="Y" GROUP BY 字段2) AA ON ABC.字段2=AA.字段2)
LEFT JOIN (SELECT 字段2, COUNT(CASE WHEN 查询= 'Y' THEN 1 ELSE NULL END) AS 查询B_NUM FROM B WHERE 查询="Y" AND 状态="Y" GROUP BY 字段2) BB ON ABC.字段2=BB.字段2)
LEFT JOIN (SELECT 字段2, COUNT(CASE WHEN 查询1= 'Y' THEN 1 ELSE NULL END) AS 查询C1_NUM, COUNT(CASE WHEN 查询2= 'Y' THEN 1 ELSE NULL END) AS 查询C2_NUM, COUNT(CASE WHEN 查询3= 'Y' THEN 1 ELSE NULL END) AS 查询C3_NUM FROM C WHERE (查询1="Y" OR 查询2="Y" OR 查询3="Y")
AND 状态="Y" GROUP BY 字段2) CC ON ABC.字段2=CC.字段2)
LEFT JOIN (SELECT 字段2, COUNT(查询="Y") AS 查询D_NUM FROM D WHERE 查询="Y" AND 状态="Y" GROUP BY 字段1,字段2) DD ON ABC.字段2=DD.字段2
查询明细:
SELECT ABC.字段1,G.字段2,G.字段3,G.字段4,G.字段5,AA.查询,BB.查询,CC.查询1,CC.查询2,CC.查询3,DD.查询 FROM
(((((SELECT 字段1 FROM A WHERE 查询="Y" AND 状态="Y"
UNION SELECT 字段1 FROM B WHERE 查询="Y" AND 状态="Y"
UNION SELECT 字段1 FROM C WHERE (查询1="Y" OR 查询2="Y" OR 查询3="Y") AND 状态="Y"
UNION SELECT 字段1 FROM D WHERE 查询="Y" AND 状态="Y") ABC
LEFT JOIN (SELECT 字段1, 查询 FROM A WHERE 状态="Y") AA ON ABC.字段1=AA.字段1)
LEFT JOIN (SELECT 字段1, 查询 FROM B WHERE 状态="Y") BB ON ABC.字段1=BB.字段1)
LEFT JOIN (SELECT 字段1, 查询1, 查询2, 查询3 FROM C WHERE 状态="Y") CC ON ABC.字段1=CC.字段1)
LEFT JOIN (SELECT 字段1, 查询 FROM D WHERE 状态="Y") DD ON ABC.字段1=DD.字段1)
LEFT JOIN (SELECT 字段1, 字段2, 字段3, 字段4, 字段5 FROM GG) G ON ABC.字段1=G.字段1
|
|