2

请原谅我的标题。我有一张这样的桌子:

在此处输入图像描述

将有数千行,现在我想选择具有相同 group_id 但 vr_debit 和 vr_credit 值不能相等的行:即;在显示的图像中,没有行满足此条件。如果有两行,例如 (6,500.000,0) 和 (6,0,600.000),我希望它们作为结果。希望你能明白。

谢谢你。

4

3 回答 3

1

使用聚合函数计算每个组并使用子句SUM()过滤它们。HAVING

SELECT  GROUP_ID, SUM(vr_debit) totalDebit, SUM(vr_credit) totalCredit
FROM    TableName
GROUP   BY GROUP_ID
HAVING  SUM(vr_debit) <> SUM(vr_credit)

如果要获取未计算的行,可以将其加入子查询。

SELECT  a.*
FROM    TableName a
        INNER JOIN
        (
            SELECT  GROUP_ID
            FROM    TableName
            GROUP   BY GROUP_ID
            HAVING  SUM(vr_debit) <> SUM(vr_credit)
        ) b ON  a.GROUP_ID = b.GROUP_ID
于 2013-04-02T12:01:02.300 回答
1

也许:

SELECT group_ID,
       vr_debit,
       vr_credit
FROM 
   dbo.TableName T1
WHERE
   EXISTS(
      SELECT 1 FROM dbo.TableName T2
      WHERE T1.group_ID = T2.group_ID
      AND   T1.vr_debit <> T2.vr_debit
      AND   T1.vr_credit<> T2.vr_credit
      AND   T1.vr_debit <> T2.vr_credit
   )
于 2013-04-02T12:05:33.507 回答
1

您也可以使用此选项

SELECT *
FROM dbo.test64 t
WHERE EXISTS (
              SELECT 1
              FROM dbo.test64 t2
              WHERE t.group_id = t2.group_id
              HAVING SUM(t2.vr_debit) - SUM(t2.vr_credit) != 0
              )

SQLFiddle上的演示

于 2013-04-02T12:20:55.847 回答