我很担心这个GROUP BY&联盟声明。
现在我得到这个O / P.
但我希望我的输出看起来像这样:
Vendor Name Purchase Order Req Qty Inward Qty
----------------------------------------------------------------------
Philips Lighting PO20140918133011 350 350
(I) Pvt Ltd
要求:
如果我的供应商为空,那么我也必须根据采购订单进行分组。 但是我得到的所有要求都不满足的输出有没有办法我只能根据采购订单进行分组。
**查询:**
SELECT
vendor_name,
purchase_order_no,
SUM(ISNULL(InwardQty,0)) AS InwardQty,
SUM(ISNULL(ReqQty,0)) ReqQty
FROM
(
SELECT
vendor_name,
pm.purchase_order_no,
ISNULL(SUM(PIIM.qty),0) AS ReqQty,
0 InwardQty
FROM
RS_Purchase_Order_Master AS PM
LEFT OUTER JOIN RS_Purchase_Invoice_Info_Master AS PIIM ON PIIM.purchase_order_no = PM.purchase_order_no
LEFT OUTER JOIN RS_Vendor_Master AS VM ON VM.vendor_id = PM.vendor_id
WHERE
IsPicreated = 1
GROUP BY
vendor_name,
pm.purchase_order_no
UNION
SELECT
NULL AS vendor_name,
purchase_order_no,
0 AS ReqQty,
ISNULL(SUM(qty),0) AS InwardQty
FROM
RS_GIN_Master
GROUP BY
purchase_order_no
)
AS A
GROUP BY
vendor_name,
purchase_order_no
任何帮助或建议都会受到赞赏。
提前谢谢
答案 0 :(得分:1)
我不知道这是否是最佳解决方案,但我会创建一个临时表(@a):
declare @a table (
purchase_order_no varchar(100),
TotalReqQty int,
TotalInwardQty int )
插入结果:
SELECT purchase_order_no,
SUM(ReqQty),
SUM(InwardQty)
FROM table
group by purchase_order_no
之后我会使用内部联接来使用这样的东西来获取供应商:
SELECT T.Vendor_Name,
A.purchase_order_no,
A.TotalReqQty,
A.TotalInwardQty
FROM @a a
inner join
( SELECT DISTINCT Vendor_Name, purchase_order_no
FROM table WHERE Vendor_Name IS NOT NULL ) T
ON A.purchase_order_no = T.purchase_order_no
答案 1 :(得分:1)
您无需创建临时表。只需从GROUP BY中删除vendor_name,然后添加MAX(vendor_name)。
SELECT
MAX(vendor_name) AS vendor_name,
purchase_order_no,
SUM(ISNULL(InwardQty,0)) AS InwardQty,
SUM(ISNULL(ReqQty,0)) AS ReqQty
FROM
(
SELECT
vendor_name,
pm.purchase_order_no,
ISNULL(SUM(PIIM.qty),0) AS ReqQty,
0 InwardQty
FROM
RS_Purchase_Order_Master AS PM
LEFT OUTER JOIN RS_Purchase_Invoice_Info_Master AS PIIM ON PIIM.purchase_order_no = PM.purchase_order_no
LEFT OUTER JOIN RS_Vendor_Master AS VM ON VM.vendor_id = PM.vendor_id
WHERE
IsPicreated = 1
GROUP BY
vendor_name,
pm.purchase_order_no
UNION
SELECT
NULL AS vendor_name,
purchase_order_no,
0 AS ReqQty,
ISNULL(SUM(qty),0) AS InwardQty
FROM
RS_GIN_Master
GROUP BY
purchase_order_no
)
AS A
GROUP BY
purchase_order_no
答案 2 :(得分:1)
如果我查看您的查询:
子查询中的联盟 - >在每个purchase_order_no的表RS_GIN_Master中得到sum(qty)
子查询 - >将2行设为单行。
试试这个:
SELECT
vendor_name,
pm.purchase_order_no,
ISNULL(SUM(PIIM.qty),0) AS ReqQty,
sum(xx.InwardQty) as InwardQty
FROM
RS_Purchase_Order_Master AS PM
LEFT OUTER JOIN RS_Purchase_Invoice_Info_Master AS PIIM ON PIIM.purchase_order_no = PM.purchase_order_no
LEFT OUTER JOIN RS_Vendor_Master AS VM ON VM.vendor_id = PM.vendor_id
LEFT JOIN (
SELECT purchase_order_no, ISNULL(SUM(qty),0) AS InwardQty
FROM RS_GIN_Master
GROUP BY purchase_order_no
) xx On xx.purchase_order_no = pm.purchase_order_no
WHERE
IsPicreated = 1
GROUP BY
vendor_name,
pm.purchase_order_no