我有2个表,其中tblProduct和tblStock
tblProduct
ProdName Price
P8 234
S7 234
M8 234
MD8oz 234
TO8 306
TO8JP 354
LR8 354
GBB8 354
GTF8 354
SS8 354
MD12 340
P750 322
S750 322
MD750 322
P300 132
S300 132
M300 132
MD NEON300 132
1.25L 228
CANS 250ML 348
CANS 330ML 552
TO355 585
LR330X12 210
G350 576
G500 760
SSE300X24 444
SSE300X12 222
PW350 254
PW500 230
PW1L 220
tblstock
ProdName Quantity INdate PriceperQty TranStatus
M300 2 2018-11-07 23:46:05.800 132 IN
M300 2 2018-11-08 11:23:34.227 132 OUT
P300 23 2018-11-08 16:52:01.260 132 IN
MD12 12 2018-11-08 16:52:10.147 340 IN
TO8JP 3 2018-11-08 16:52:18.843 354 IN
SSE300X24 13 2018-11-08 16:52:28.587 444 IN
P8 43 2018-11-08 16:52:37.237 234 IN
1.25L 21 2018-11-08 16:52:43.843 228 IN
P8 32 2018-11-08 16:52:50.050 234 IN
S7 43 2018-11-08 16:52:54.900 234 IN
S7 32 2018-11-08 16:53:07.460 234 IN
P8 23 2018-11-08 16:53:19.020 234 IN
我想从这两个表中产生如下结果。
答案 0 :(得分:3)
您可以尝试使用ROW_NUMBER
窗口函数为tblstock
表创建行号。
然后使用条件聚合函数进行枢轴操作。
SELECT ProdName,
[1st load],
[2st load],
[3st load],
[4st load],
price,
(([1st load]+[2st load] +[3st load]+[4st load]) * price) 'Total'
FROM (
SELECT t1.ProdName,
MAX(CASE WHEN t2.rn = 1 then t2.Quantity ELSE 0 END) '1st load',
MAX(CASE WHEN t2.rn = 2 then t2.Quantity ELSE 0 END) '2st load',
MAX(CASE WHEN t2.rn = 3 then t2.Quantity ELSE 0 END) '3st load',
MAX(CASE WHEN t2.rn = 4 then t2.Quantity ELSE 0 END) '4st load',
t1.Price
FROM tblProduct t1
LEFT JOIN (
SELECT *,ROW_NUMBER() over(partition by ProdName order by INdate desc) rn
FROM tblstock
) t2 on t1.ProdName = t2.ProdName
GROUP BY t1.ProdName,t1.Price
)t1