【问题标题】:alternative to sum in sql where clause替代 sql where 子句中的 sum
【发布时间】:2014-08-25 14:11:49
【问题描述】:

我有 table1 代表订单摘要。在 table1 中,table2 与 table2 具有一对多的关系,代表订单中的不同项目。 table1 有一个数量字段,该字段应表示作为订单一部分的单个项目的总数。在表 2 中,数量字段表示该项目类型的单个项目的数量。

我想看看什么不符合这条规则(我有理由相信这条规则被打破了)

SELECT table1.id, table1.quantity, table2.orderid, table2.itemqty
FROM table1
INNER JOIN table2 on tabel1.id = table2.orderid
WHERE table1.quantity != SUM(table2.itemqty)

【问题讨论】:

    标签: sql sql-server sum


    【解决方案1】:

    您可以使用having 子句将条件应用于组:

    select  t1.id
    ,       t1.customer
    ,       t1.quantity 
    ,       sum(t2.itemqty)
    from    table1 t1
    join    table2 t2
    on      t1.id = t2.orderid
    group by
            t1.id
    ,       t1.customer
    ,       t1.quantity 
    having  t1.quantity <> sum(t2.itemqty)
    

    【讨论】:

    • 如何查看更多字段?假设我有 t1.customer
    • 您可以group byt1 中选择的任何列,在答案中更新
    【解决方案2】:
    SELECT     table1.id, 
               table1.quantity, 
               table2.orderid, 
               table2.itemqty
    FROM       table1
    INNER JOIN ( 
                   SELECT orderid,
                          SUM(itemqty) as itemqty 
                   FROM   table2 
                   GROUP BY orderid
               ) table2 
               on tabel1.id = table2.orderid
    WHERE      table1.quantity <> table2.itemqty
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-30
      • 2013-04-22
      • 2017-07-11
      • 1970-01-01
      • 2015-11-03
      • 2021-04-06
      • 1970-01-01
      • 2020-11-29
      相关资源
      最近更新 更多