隐藏

sql 的一种复合查询方法 allitem

发布:2015/1/4 13:55:49作者:管理员 来源:本站 浏览次数:1398

这条语句在多表查询时很有用!

语句如下:

select * from (

select * from 表名

) allitem

order by id


如今天写的一个sql语句:

select INVMC.MC001'品号',INVMB.MB002'品名',INVMB.MB004'单位',SUM(INVMC.MC004)'安全存量 ',SUM(INVMC.MC007)'现有存量',SUM(INVMC.MC004)-SUM(INVMC.MC007)'需补货数量',TD008' 已下单数量'
FROM INVMB JOIN INVMC ON MB001=MC001
JOIN PURTD ON TD004=MC001
WHERE MC002<>'F000' AND MC002<>'H000' AND TD001='331'
GROUP BY MC001,MB002,MB004,TD008
HAVING SUM(INVMC.MC007)<SUM(INVMC.MC004)

union

select * from
(
   select INVMC.MC001'品号',INVMB.MB002'品名',INVMB.MB004'单位',SUM(INVMC.MC004)'安全存量 ',SUM(INVMC.MC007)'现有存量',SUM(INVMC.MC004)-SUM(INVMC.MC007)'需补货数量 ',INVMC.UDF51'已下单数量'
   FROM INVMB JOIN INVMC ON MB001=MC001
   WHERE MC002<>'F000' AND MC002<>'H000'
   GROUP BY MC001,MB002,MB004,INVMC.UDF51
   HAVING SUM(INVMC.MC007)<SUM(INVMC.MC004)
)allitem

where 品号 not in (

select 品号 from

    (
     select INVMC.MC001'品号',INVMB.MB002'品名',INVMB.MB004'单位',SUM(INVMC.MC004)'安全存量 ',SUM(INVMC.MC007)'现有存量',SUM(INVMC.MC004)-SUM(INVMC.MC007)'需补货数量',TD008' 已下单数量'
     FROM INVMB JOIN INVMC ON MB001=MC001
     JOIN PURTD ON TD004=MC001
     WHERE MC002<>'F000' AND MC002<>'H000' AND TD001='331'
     GROUP BY MC001,MB002,MB004,TD008
     HAVING SUM(INVMC.MC007)<SUM(INVMC.MC004)
    )allitem
   )