我有以下代码,我们需要在17个不同的位置查看我们的库存。我下面的代码仅适用于5个位置,但有效。期待我们可以使用更清晰,更高效的代码来获得相同的结果。
SELECT DISTINCT imitmidx_sql.item_no, imitmidx_sql.item_desc_1, imitmidx_sql.item_desc_2,
(SELECT qty_on_hand FROM iminvloc_sql AS IMINVLOC_SQL_1 WHERE (loc = '1') AND (item_no = imitmidx_sql.item_no)) AS Loc1,
(SELECT qty_on_hand FROM iminvloc_sql AS IMINVLOC_SQL_2 WHERE (loc = '2') AND (item_no = imitmidx_sql.item_no)) AS Loc2,
(SELECT qty_on_hand FROM iminvloc_sql AS IMINVLOC_SQL_3 WHERE (loc = '3') AND (item_no = imitmidx_sql.item_no)) AS Loc3,
(SELECT qty_on_hand FROM iminvloc_sql AS IMINVLOC_SQL_4 WHERE (loc = '4') AND (item_no = imitmidx_sql.item_no)) AS Loc4,
(SELECT qty_on_hand FROM iminvloc_sql AS IMINVLOC_SQL_5 WHERE (loc = '5') AND (item_no = imitmidx_sql.item_no)) AS Loc5
FROM iminvloc_sql INNER JOIN imitmidx_sql ON iminvloc_sql.item_no = imitmidx_sql.item_no
答案 0 :(得分:0)
怎么样:
select
imitmidx_sql.item_no,
imitmidx_sql.item_desc_1,
imitmidx_sql.item_desc_2,
itm_loc_qty.*
from iminvloc_sql
pivot (SUM(qty_on_hand) for loc in ([1],[2],[3],[4],[5])) as itm_loc_qty -- Add here as necessary
join imitmidx_sql
on itm_loc_qty.item_no = imitmidx_sql.item_no