4

I have a part table where I have 5 fields. I want to sum the QTY of the mfgpn while showing the first returned row for the other 3 fields (Manfucturer, DateCode, Description). I initially thought of using the MIN function as follows, but that doesn't really help me insofar as that the data is not a int data type. How would I go about doing this? Right now I'm stuck at the following query below:

SELECT SUM([QTY]) AS QTY
  ,[MFGPN]
  ,MIN([MANUFACTURER]) AS MANUFACTURER
  ,MIN([DATECODE]) AS DateCode
  ,MIN([DESCRIPTION]) AS DESCRIPTION
  INTO part
GROUP BY MFGPN, MANUFACTURER, DATECODE, description
ORDER BY mfgpn ASC
4

2 回答 2

4

CROSS APPLY为你工作吗?

SELECT 
    SUM(a.[QTY]) AS QTY
    ,a.[MFGPN]
    ,c.[MANUFACTURER]
    ,c.[DATECODE]
    ,c.[DESCRIPTION]
FROM part a
    CROSS APPLY (SELECT TOP 1 * FROM part b WHERE a.[MFGPN] = b.[MFGPN]) c
GROUP BY 
    a.[MFGPN]
    ,c.[MANUFACTURER]
    ,c.[DATECODE]
    ,c.[DESCRIPTION]

经以下测试:

DECLARE @T1 AS TABLE (
    [QTY] int
    ,[MFGPN] NVARCHAR(50)
    ,[MANUFACTURER] NVARCHAR(50)
    ,[DATECODE] DATE
    ,[DESCRIPTION] NVARCHAR(50));

INSERT @T1 VALUES
(2, 'MFGPN-1', 'MANUFACTURER-A', '20120101', 'A-1'),
(4, 'MFGPN-1', 'MANUFACTURER-B', '20120102', 'B-1'),
(3, 'MFGPN-1', 'MANUFACTURER-C', '20120103', 'C-1'),
(1, 'MFGPN-2', 'MANUFACTURER-A', '20120101', 'A-2'),
(5, 'MFGPN-2', 'MANUFACTURER-B', '20120101', 'B-2')

SELECT 
    SUM(a.[QTY]) AS QTY
    ,a.[MFGPN]
    ,c.[MANUFACTURER]
    ,c.[DATECODE]
    ,c.[DESCRIPTION]
FROM @T1 a
    CROSS APPLY (SELECT TOP 1 * FROM @T1 b WHERE a.[MFGPN] = b.[MFGPN]) c
GROUP BY 
    a.[MFGPN]
    ,c.[MANUFACTURER]
    ,c.[DATECODE]
    ,c.[DESCRIPTION]

生产

QTY MFGPN   MANUFACTURER    DATECODE    DESCRIPTION
9   MFGPN-1 MANUFACTURER-A  2012-01-01  A-1
6   MFGPN-2 MANUFACTURER-A  2012-01-01  A-2
于 2012-07-24T00:26:53.800 回答
0

这可以通过窗口 SUM()轻松管理:

WITH summed_and_ranked AS (
  SELECT
    MFGPN,
    MANUFACTURER,
    DATECODE,
    DESCRIPTION,
    QTY = SUM(QTY) OVER (PARTITION BY MFGPN),
    RNK = ROW_NUMBER() OVER (
      PARTITION BY MFGPN
      ORDER BY DATECODE  -- or which column should define the order?
    )
  FROM atable
)
SELECT
  MFGPN,
  MANUFACTURER,
  DATECODE,
  DESCRIPTION,
  QTY,
INTO parts
FROM summed_and_ranked
WHERE RNK = 1
;

对于每一行,计算组的总数量和组内的排名。当实际获取要插入新表(主 SELECT)的行时,只会RNK拉取值为 1 的行。因此,您会得到一个包含组总数以及某些行的详细信息的结果集。

于 2012-07-24T08:50:23.453 回答