SQL Group BY SUM一列并选择第一行的分组项

时间:2012-07-24 00:16:21

标签: sql sql-server sql-server-2008

我有一个零件表,我有5个字段。我想要显示mfgpn的QTY,同时显示其他3个字段的第一个返回行(Manfucturer,DateCode,Description)。我最初想到如下使用MIN函数,但这并不能真正帮助我,因为数据不是int数据类型。我该怎么做呢?现在我坚持下面的查询:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

可以使用windowed 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的行。因此,您将获得包含组总计的结果集以及某些行的详细信息。