SELECT
DATEPART(YEAR, tblGRN.GRNApproveDate) AS Year,
tblGRNMaterials.MaterialCode,
tblMaterial.MaterialDescription,
SUM(tblGRNMaterials.NetQty) AS Qty
FROM
tblGRN
INNER JOIN
tblGRNMaterials ON tblGRN.GRNNO = tblGRNMaterials.GRNNO
INNER JOIN
tblMaterial ON tblGRNMaterials.MaterialCode = tblMaterial.MaterialCode
WHERE
(tblGRN.GRNStoreID = 'RM_Main')
AND (tblGRN.GRNStatus = 1)
AND (CONVERT(DATE, tblGRN.GRNApproveDate) BETWEEN '2017-01-01' AND '2018-12-31')
GROUP BY
tblGRNMaterials.MaterialCode, tblMaterial.MaterialDescription,
DATEPART(YEAR, tblGRN.GRNApproveDate)
ORDER BY
tblGRNMaterials.MaterialCode
我的输出
Year MaterialCode MaterialDescription Qty
-------------------------------------------------------------
2017 LM/CCM/SO Cellulose C. Methyl 200.000
2018 LM/CCM/SO Cellulose C. Methyl 350.000
2017 LM/MAG/PW Magnesium Stearate 175.000
2018 LM/MAG/PW Magnesium Stearate 250.000
2017 LM/MCC/PW Micro Crystal Cellulose 75.000
2018 LM/MCC/PW Micro Crystal Cellulose 0.320
我需要选择每年持有“数量”最大值的年份,并将其与2017年和2018年进行比较
结果应为:
Year MaterialCode MaterialDescription Qty
----------------------------------------------------------
2018 LM/CCM/SO Cellulose C. Methyl 350.000
2018 LM/MAG/PW Magnesium Stearate 250.000
2017 LM/MCC/PW Micro Crystal Cellulose 75.000
答案 0 :(得分:1)
首先,我将这样编写查询:
SELECT year(g.GRNApproveDate) AS Year, gm.MaterialCode,
m.MaterialDescription, SUM(gm.NetQty) AS Qty
FROM tblGRN g INNER JOIN
tblGRNMaterials gm
ON g.GRNNO = gm.GRNNO INNER JOIN
tblMaterial m
ON gm.MaterialCode = m.MaterialCode
WHERE g.GRNStoreID = 'RM_Main' AND
g.GRNStatus = 1 AND
g.GRNApproveDate >= '2017-01-01' AND
g.GRNApproveDate < '2019-01-01'
GROUP BY gm.MaterialCode, m.MaterialDescription, year(g.GRNApproveDate)
ORDER BY gm.MaterialCode;
虽然不是性能最高的方法,但最简单的方法可能是:
SELECT TOP (1) WITH TIES, year(g.GRNApproveDate) AS Year, gm.MaterialCode,
m.MaterialDescription, SUM(gm.NetQty) AS Qty
FROM tblGRN g INNER JOIN
tblGRNMaterials gm
ON g.GRNNO = gm.GRNNO INNER JOIN
tblMaterial m
ON gm.MaterialCode = m.MaterialCode
WHERE g.GRNStoreID = 'RM_Main' AND
g.GRNStatus = 1 AND
g.GRNApproveDate >= '2017-01-01' AND
g.GRNApproveDate < '2019-01-01'
GROUP BY gm.MaterialCode, m.MaterialDescription, year(g.GRNApproveDate)
ORDER BY ROW_NUMBER() OVER (PARTITION BY gm.MaterialCode ORDER BY SUM(gm.NetQty) DESC);