SQL查询中的求和

时间:2014-03-14 08:45:38

标签: sql-server sql-server-2000

我从数据库SQL SERVER 2000获得此查询:

SELECT D.KODDESIGNASI AS KJB_KODKAT,  
(SELECT ISNULL((SELECT SUM(AJW_HAK) FROM AGIHANJPAT WHERE AJW_KODALAT=K.KODALAT),0))     
AS PERJAWATAN
FROM KAT_PERALATAN AS K, KOD_PERALATAN AS A, DESIGNASI AS D 
WHERE K.KODKATEGORI=A.KODKATEGORI AND A.KODDESIGNASI=D.KODDESIGNASI AND   
D.KODDESIGNASI='BST'
ORDER BY D.PERIHAL

从这个查询中,我得到了这个结果

KJB_KODKAT    PERJAWATAN
------------------------
BST           2
BST           6
BST           1265
BST           54
...           ...
...           ...
...           ...

现在,我希望获得PERJAWATAN WHERE D.KODDESIGNASI='BST'的总价值。 我尝试像这样修改我的查询:

SELECT D.KODDESIGNASI AS KJB_KODKAT,  
SUM(SELECT ISNULL((SELECT SUM(AJW_HAK) FROM AGIHANJPAT WHERE 
        AJW_KODALAT=K.KODALAT),0)))     
AS PERJAWATAN
FROM KAT_PERALATAN AS K, KOD_PERALATAN AS A, DESIGNASI AS D 
WHERE K.KODKATEGORI=A.KODKATEGORI AND A.KODDESIGNASI=D.KODDESIGNASI AND   
D.KODDESIGNASI='BST'
ORDER BY D.PERIHAL

然而,我收到了错误。任何人都可以帮我修复错误吗?我对SQL SERVER 2000非常陌生。它与MYSQL不同吗?

2 个答案:

答案 0 :(得分:0)

    select KJB_KODKAT, SUM(PERJAWATAN)    
    from (
    SELECT D.KODDESIGNASI AS KJB_KODKAT,  
    (SELECT ISNULL((SELECT SUM(AJW_HAK) FROM AGIHANJPAT WHERE AJW_KODALAT=K.KODALAT),0))     
    AS PERJAWATAN
    FROM KAT_PERALATAN AS K, KOD_PERALATAN AS A, DESIGNASI AS D 
    WHERE K.KODKATEGORI=A.KODKATEGORI AND A.KODDESIGNASI=D.KODDESIGNASI AND   
    D.KODDESIGNASI='BST'
    ORDER BY D.PERIHAL) Z
group by KJB_KODKAT

试试这个

答案 1 :(得分:0)

试试这个。

SELECT KJB_KODKAT, SUM(PERJAWATAN)
FROM
(
SELECT  D.KODDESIGNASI AS KJB_KODKAT,  
        (SELECT ISNULL((SELECT SUM(AJW_HAK) FROM AGIHANJPAT WHERE AJW_KODALAT=K.KODALAT),0))AS PERJAWATAN
FROM    KAT_PERALATAN AS K, KOD_PERALATAN AS A, DESIGNASI AS D 
WHERE   K.KODKATEGORI=A.KODKATEGORI 
        AND A.KODDESIGNASI=D.KODDESIGNASI 
        AND D.KODDESIGNASI='BST'
)SourceQuery

这应该可行,但是,您应该使用连接而不是原始代码。