我有一个我想要PIVOT的交易表(按月数量)。以下查询执行正常,但它排除了Tx表中没有值(并且不存在)的项目。我首先使用了GIP表(所有项目的完整列表和关于每个项目的各种信息)并将Tx表加入其中,但这不起作用。我还尝试了LEFT OUTER JOIN,并在WHERE子句中添加了NULL限定符。 如果有人可以按顺序将其转换为月份的动态查询,则可以获得奖励。
SELECT
CAST([item_no] AS INT) 'IMF',
[1] AS 'Jan',
[2] AS 'Feb',
[3] AS 'Mar',
[4] AS 'Apr',
[5] AS 'May',
[6] AS 'Jun',
[7] AS 'Jul',
[8] AS 'Aug',
[9] AS 'Sep',
[10] AS 'Oct',
[11] AS 'Nov',
[12] AS 'Dec'
FROM
(SELECT
GIP.[Station__No],
GIP.[generic_inventory],
GIP.[item_no],
(Tx.[Quantity]*-1) Qty,
MONTH(Tx.[Date_Posted]) TMonth
FROM
[Surgery].[genericx_inventory_item_445_01] GIP
LEFT JOIN [CDWWork].[IFCAP].[inventory_transaction_445_2] Tx ON Tx.[station__no] = GIP.[station__no] AND Tx.[Inventory_Point] = GIP.[generic_inventory] AND GIP.[Itemnox] = Tx.[Item_no]
where GIP.[Station__no] = 658
and Tx.[Date_Posted] >= '7/01/16'
and Tx.[Date_Posted] <= '6/30/17'
and GIP.[generic_inventory] = 623
) As x
PIVOT
(
SUM(Qty)
FOR TMonth
IN( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
)P
答案 0 :(得分:0)
这与枢轴无关LEFT JOIN
错误。 second 表中的条件必须在ON
子句中:
FROM [Surgery].[genericx_inventory_item_445_01] GIP LEFT JOIN
[CDWWork].[IFCAP].[inventory_transaction_445_2] Tx
ON Tx.[station__no] = GIP.[station__no] AND
Tx.[Inventory_Point] = GIP.[generic_inventory] AND
GIP.[Itemnox] = Tx.[Item_no] AND
Tx.[Date_Posted] >= '2016-07-01' AND
Tx.[Date_Posted] <= '2017-06-30'
WHERE GIP.[Station__no] = 658 AND GIP.[generic_inventory] = 623
当您使用它时,您应该使用标准日期格式。不那么模棱两可(更容易阅读;)。