日期:2014-05-18  浏览次数:20513 次

大家帮我看一条sql语句
SELECT  
        NAME,
        Q_QUNIANBF=SUM(Q_QUNIANBF),
        BAOFEI_BAOFEI=SUM(BAOFEI_BAOFEI)

FROM
(
        SELECT   Q_NAME   AS   NAME,Q_QUNIANBF,0   AS   BAOFEI_BAOFEI   FROM   qunianbf
        UNION   ALL
        SELECT   RLZY_NAME   AS   NAME,0   AS   Q_QUNIANBF,BAOFEI_BAOFEI   FROM   BAOFEI

)f
GROUP   BY   NAME

NAME                 Q_QUNIANBF   BAOFEI_BAOFEI
-------------   -----------   -------------
王麻1                 15000               5111
王五                   300000             4000
赵钱                     1111                 5222

(3   行受影响)

如果我要在加上一个baofei_baofei的累加之合。条件有两个。一个是BAOFEI表里的日期baofei.baofei_tjdate   between   '2007-01-1 '   and   '2007-12-31 '和baofei.baofei_xianzhong= '车辆   我应该怎么去加呢。


------解决方案--------------------
--try

SELECT
NAME,
Q_QUNIANBF=SUM(Q_QUNIANBF),
BAOFEI_BAOFEI=SUM(BAOFEI_BAOFEI),
baofei_baofei2=(select sum(baofei_baofei) from BAOFEI
where RLZY_NAME=f.RLZY_NAME and baofei_tjdate between '2007-01-1 ' and '2007-12-31 ' and baofei_xianzhong= '车辆 ')
FROM
(
SELECT Q_NAME AS NAME,Q_QUNIANBF,0 AS BAOFEI_BAOFEI FROM qunianbf
UNION ALL
SELECT RLZY_NAME AS NAME,0 AS Q_QUNIANBF,BAOFEI_BAOFEI FROM BAOFEI
)f
GROUP BY NAME
------解决方案--------------------
SELECT
NAME,
Q_QUNIANBF=SUM(Q_QUNIANBF),
BAOFEI_BAOFEI=SUM(BAOFEI_BAOFEI)

FROM
(
SELECT Q_NAME AS NAME,Q_QUNIANBF,0 AS BAOFEI_BAOFEI FROM qunianbf
UNION ALL
SELECT RLZY_NAME AS NAME,0 AS Q_QUNIANBF,BAOFEI_BAOFEI FROM BAOFEI where baofei_tjdate between '2007-01-1 ' and '2007-12-31 ' and baofei_xianzhong= '车辆 '
) f
GROUP BY NAME