5

我在 sql server 上有一组数据,例如:

ID ID_Invoice Article Quantity Status
1  10         carrot  10       null
2  10         carrot  5        C
3  10         onion   8        null
4  10         onion   4        C
5  11         tomato  20       null
6  11         tomato  18       C
7  11         onion   2        null
8  11         onion   1        C

这意味着客户订购了 10 个胡萝卜和 8 个洋葱(在一张发票上),但实际上只收到了 5 个胡萝卜和 4 个洋葱。如果 status 为 null 则为原始数量,如果 status 为 C 则为更正数量

我需要生成一个像

ID ID_Invoice Article Quantity 
1  10         carrot  -5       
2  10         onion   -4
3  11         tomato  -2
4  11         onion   -1

它显示了每张发票上的订购数量和实际数量之间的差异。我不知道如何开始。任何帮助深表感谢:)

4

4 回答 4

8

带有简单CASE表达式的选项,没有过多的 JOIN

SELECT ID_Invoice, Article, 
       SUM(CASE WHEN Status IS NULL 
  THEN -1 * Quantity ELSE Quantity END) AS Quantity
FROM dbo.test38
GROUP BY ID_Invoice, Article

结果:

ID_Invoice Article Quantity 
10  carrot  -5
10  onion   -4
11  onion   -1
11  tomato  -2

SQLFiddle上的演示

于 2013-03-15T11:05:54.307 回答
2

您没有指定您使用的是哪个 RDBMS,但我的回答是符合 ANSI-SQL 标准的 :) 适用于所有有效的 RDBMS。

SELECT
yt1.ID_Invoice, 
yt1.Article,
yt2.Quantity - yt1.Quantity AS Quantity
FROM
yourTable yt1
INNER JOIN yourTable yt2 ON yt1.ID_Invoice = yt2.ID_Invoice 
                            AND yt1.Article = yt2.Article 
                            AND yt2.Status = 'C'
WHERE
yt1.Status IS NULL

这个答案是假设,总是有一条状态为 NULL 的记录和相应的状态为“C”的行。如果不是这种情况,您必须像这样调整它:

SELECT
yt1.ID_Invoice, 
yt1.Article,
CASE WHEN yt2.Quantity IS NULL THEN yt1.Quantity ELSE yt2.Quantity - yt1.Quantity END AS Quantity
FROM
yourTable yt1
LEFT JOIN yourTable yt2 ON yt1.ID_Invoice = yt2.ID_Invoice 
                            AND yt1.Article = yt2.Article 
                            AND yt2.Status = 'C'
WHERE
yt1.Status IS NULL
于 2013-03-15T10:57:39.793 回答
2

最少的资源密集型:

SELECT id_invoice
, article
, org_quantity
, new_quantity
, new_quantity - org_quantity diff
FROM (SELECT id_invoice
      , article
      , max(CASE WHEN status IS NULL THEN quantity else null END) org_quantity
      , max(CASE WHEN status = 'C' THEN quantity else null END) new_quantity
      FROM   orders
      GROUP BY id_invoice
      , article)

看到它在这里工作:http ://sqlfiddle.com/#!4/f96adf/14

于 2013-03-15T11:02:40.240 回答
1

因此,首先您必须通过进行 2 个查询将实际订单与订单分开,然后您必须将订单与实际订单分开.. 像这样

select 
   Recived.ID, 
   Recived.ID_Invoice,
   Recived.Article,
   Recived.Quantity - Ordered.Quantity as Quantity
from
   (select * from dataTable where Status is null) as Ordered
   left join (select * from  dataTable where Status = 'C')  as Recived on (Ordered.ID_Invoice = Recived.ID_Invoice and Ordered.Article = Recived.Article )

笔记!如果每篇文章都有一个 id 用于“左连接”而不是比较 varchars,你会更好。

这是一个小提琴示例: http ://sqlfiddle.com/#!2/16666/1

于 2013-03-15T10:56:14.637 回答