我有一个物料清单表,希望在其中插入基于ParentItemCode
的销售价格(仅在第一行中一次)。
父项X
的价格是1735,Y
的价格是3000。
以下是数据:
CREATE TABLE mytable (
LineNum INT NOT NULL PRIMARY KEY
,ParentPnxCode VARCHAR(1) NOT NULL
,ChildPnxCode VARCHAR(2) NOT NULL
,Unit VARCHAR(3) NOT NULL
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
10000
,'X'
,'x1'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
20000
,'X'
,'x2'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
30000
,'X'
,'x3'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
40000
,'X'
,'x4'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
50000
,'X'
,'x5'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
60000
,'X'
,'x6'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
70000
,'X'
,'x7'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
5000
,'Y'
,'y1'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
7500
,'Y'
,'y2'
,'PCS'
);
INSERT INTO mytable (
LineNum
,ParentPnxCode
,ChildPnxCode
,Unit
)
VALUES (
8750
,'Y'
,'y2'
,'PCS'
);
以下是所需的输出:
+---------+---------------+--------------+------+-------------------+
| LineNum | ParentPnxCode | ChildPnxCode | Unit | Old Selling Price |
+---------+---------------+--------------+------+-------------------+
| 10000 | X | x1 | PCS | 1735 |
| 20000 | X | x2 | PCS | 0 |
| 30000 | X | x3 | PCS | 0 |
| 40000 | X | x4 | PCS | 0 |
| 50000 | X | x5 | PCS | 0 |
| 60000 | X | x6 | PCS | 0 |
| 70000 | X | x7 | PCS | 0 |
| 5000 | Y | y1 | PCS | 3000 |
| 7500 | Y | y2 | PCS | 0 |
| 8750 | Y | y2 | PCS | 0 |
+---------+---------------+--------------+------+-------------------+
您能帮我实现上述输出吗?感谢您的提前支持。
答案 0 :(得分:1)
此查询应为您提供所需的结果。它依靠ROW_NUMBER()
来确定当前记录是否是该组中的第一条记录,并相应地显示期望值:
SELECT
t.*,
CASE
WHEN ROW_NUMBER() OVER(PARTITION BY ParentPnxCode ORDER BY LineNum) = 1
THEN CASE ParentPnxCode
WHEN 'X' THEN 1735
WHEN 'Y' THEN 3000
END
ELSE 0
END OldSellingPrice
FROM mytable t
LineNum | ParentPnxCode | ChildPnxCode | Unit | OldSellingPrice ------: | :------------ | :----------- | :--- | --------------: 10000 | X | x1 | PCS | 1735 20000 | X | x2 | PCS | 0 30000 | X | x3 | PCS | 0 40000 | X | x4 | PCS | 0 50000 | X | x5 | PCS | 0 60000 | X | x6 | PCS | 0 70000 | X | x7 | PCS | 0 5000 | Y | y1 | PCS | 3000 7500 | Y | y2 | PCS | 0 8750 | Y | y2 | PCS | 0
如果您希望在表中实际创建一个新列来存储该信息,则可以这样做(ROW_NUMBER()
子句中不允许使用{SET
,我将子句切换为带有{{ 1}}条件):
NOT EXISTS
答案 1 :(得分:0)
如果父项的价格存储在主表中。
SELECT LineNum, ParentPnxCode, ChildPnxCode, Unit,
Old_Selling_Price = IIF((LAG(ParentPnx_Price) OVER(PARTITION BY mytable.ParentPnxCode ORDER BY mytable.ParentPnxCode) IS NULL),ParentPnx_Price,0)
FROM mytable
INNER JOIN ParentPnx_Master ON mytable.ParentPnxCode = ParentPnx_Master.ParentPnxCode
ORDER BY mytable.ParentPnxCode