我需要一些SQL来创建导出文件。我有很多工作应该如此。一个主要障碍是WITH ROLLUP
部分。
我需要通过VendorNo(商店)和DepartmentID(部门)获得总计,但不需要总计。通过获取列的前3位数来收集部门,如下所示。对此进行分组以及VendorNo正在给我我需要的东西,但也会在那里投入总数。
如何从WITH ROLLUP
中减去总计总数或者重写某些部分以实现每个VendorNo,Dept的相同总计?
到目前为止,我有:
select
'VDP' as [Record Id],
'TRU' as [Client Id],
o.vendorNo as [Store Number],
CASE WHEN LEFT(HVI.EncodeData, 3) IS NULL THEN 'S' ELSE 'D' END as [Feed Level],
LEFT(HVI.EncodeData, 3) AS [DepartmentId],
CONVERT(Date, pto.PrintBatch) as [Metric Date],
CASE WHEN pto.pickbit = 1 THEN 'ISPU_ORDER_PICKUP' ELSE 'ISPU_ORDER_CREATED' END as [Metric ID], -- 15 chars ISPU_ORDER_CREATED or ISPU_ORDER_PICKUP TOTO: VALIDATE THIS WORKS !!
'A' AS [Metric Category],
'D' AS [Metric Granularity],
REPLICATE('0', 9 - len(CAST(SUM(OI.Quantity) AS int))) + CAST(CAST(SUM(OI.Quantity) as Int)as VARCHAR) AS [Data Value 1], -- needed to get the left-padded 9 char max value
NULL as [Data Value 2],
NULL as [Data Value 3],
NULL as [Data Value 4],
NULL as [Data Value 5],
NULL as [Data Value 6],
NULL as [Operation Code]
FROM
pickticketsorders pto
inner join orders o
on pto.orderno = o.orderno
and o.rank = 3
and pto.printbatch >= '6-12-2015'
and pto.printbatch < '6-13-2015'
INNER JOIN HostVendorItems HVI
on HVI.ItemId = pto.ItemId
INNER JOIN OrderItems OI
on OI.OrderNo = o.OrderNo
GROUP BY
o.VendorNo,
LEFT(HVI.EncodeData, 3),
pto.PrintBatch,
pto.PickBit
WITH ROLLUP
ORDER BY
o.VendorNo,
DepartmentId ,
pto.PrintBatch
答案 0 :(得分:3)
使用GROUPING SETS
。我不确定你想要哪些群体,但这似乎与你要求的相符:
GROUP BY GROUPING SETS ((o.VendorNo, LEFT(HVI.EncodeData, 3), pto.PrintBatch, pto.PickBit),
(o.VendorNo, LEFT(HVI.EncodeData, 3)),
(o.VendorNo)
)
您可能希望详细了解documentation中的GROUPING SETS
。
答案 1 :(得分:0)
您还可以添加:
HAVING GROUPING(o.VendorNo) = 0