使一行的价格成为所有行的价格

时间:2014-06-09 12:43:46

标签: mysql

我刚开始使用mysql for SAP。

我想得到这个结果:

DocEntry Description Price
00001    item A      100.00
00003    item C      110.00

从这个数据

DocEntry  Description Quantity Price
00001     item A       2       300.00
00001     freight      -       100.00
00002     item A       1       300.00
00003     item C       1       300.00
00003     freight      -       110.00

我试图通过以下方式过滤货物:

create view table_a 
as 
select DocEntry, Description, Price 
from inv1 where Description like 'freight'

create view table_b 
as 
select DocEntry, Description, Price
from inv1
where exist (select * from table_a where table_a.DocEntry = table_b.DocEntry  

我不知道如何处理价格?

谢谢!

2 个答案:

答案 0 :(得分:1)

看起来您希望运费适合每个项目:

select distinct a.DocEntry, a.Description, b.Price
from inv1 a
join inv1 b on a.DocEntry = b.DocEntry
where a.Description != 'freight'
and b.Description = 'freight'

虽然数据不需要它,但是如果每个“运费”行有多个“项”行,则添加distinct关键字。如果不可能发生这种情况,可以删除distinct

答案 1 :(得分:0)

目前还不是很清楚你在问什么,但也许是这样......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(DocEntry INT NOT NULL,  Description VARCHAR(12) NOT NULL, Quantity INT NULL,Price INT NOT NULL,PRIMARY KEY(DocEntry,Description));

INSERT INTO my_table VALUES
(1,'item A',2,300),
(1,'freight',NULL,100),
(2,'item A',1,300),
(3,'item C',1,300),
(3,'freight',NULL,110);

mysql> SELECT * FROM my_table;
+----------+-------------+----------+-------+
| DocEntry | Description | Quantity | Price |
+----------+-------------+----------+-------+
|        1 | freight     |     NULL |   100 |
|        1 | item A      |        2 |   300 |
|        2 | item A      |        1 |   300 |
|        3 | freight     |     NULL |   110 |
|        3 | item C      |        1 |   300 |
+----------+-------------+----------+-------+

SELECT docentry
     , MAX(CASE WHEN description = 'freight' THEN price END) price
     , MAX(CASE WHEN quantity IS NOT NULL THEN description END) description 
  FROM my_table 
 GROUP 
    BY docentry 
HAVING price IS NOT NULL;
+----------+-------+-------------+
| docentry | price | description |
+----------+-------+-------------+
|        1 |   100 | item A      |
|        3 |   110 | item C      |
+----------+-------+-------------+