2

我有一个包含交易列表(发票和信用)的表格,我需要获取发票和信用不匹配的所有行的列表。

例如

user     product    value
bill     ThingA     200
jim      ThingA    -200
sue      ThingB     100
liz      ThingC      50

我只想看到第三行和第四行,因为其他行的值匹配。

如果我选择 product, sum(value) ... 按具有 sum(value) <> 0 的产品分组,我可以这样做

效果很好,但我也想返回用户名。

一旦我将用户添加到选择中,我也需要按它进行分组,这会导致数量与用户和产品不匹配,这会造成混乱。

有任何想法吗 ?我正在使用 MS SQL 2000...

干杯

4

2 回答 2

1

你可以这样做:

  SELECT tab2.user, product, sum_val
  FROM 
     (SELECT product, SUM(value) sum_val 
     FROM your_table
     GROUP BY product HAVING SUM(value) <> 0) tab1 
  INNER JOIN your_table tab2 
  ON tab1.product = tab2.product
于 2012-11-06T16:52:46.700 回答
0

@LolCoder solution is good, but given a context where you have "Thing B" with a "100" value by both "sue" and "liz", you could be able to retrieve the following resultset with my query :

| product | value | users    |
+----------------------------+
| Thing B | 200   | sue, liz |

Here is the query :

select product
      ,sum(value) as value
      ,Stuff(( select ',' + convert(varchar(40), SQ.user)
                 from YourTable SQ
                where Q.product = SQ.product
                for xml path('')
            ), 1, 1, '') as users
  from YourTable Q
 group by Q.product
于 2012-11-06T17:59:15.530 回答