Требуется одна строка данных, но группировка по ней не оказывает такого влияния - PullRequest
0 голосов
/ 13 марта 2019

Я хочу просто вернуть одну строку данных с суммой данных, а также сгруппировать по идентификатору элемента производственного плана, в идеале, мне нужна строка, показывающая мне это поле и значение суммы qty, поэтому оно должно иметь значение

ProductionPlanItemId    QtyCompleted
5865406                 3  

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT [CompletedPrintedId]
      ,[UserName]
      ,[ProductionPlanId]
      ,[QtyCompleted]
      ,[SubAssembledQty]
      ,[QtyRequired]
      ,[ProductionPlanItemID]
      ,[SOPOrderReturnLineId]
FROM [CompletedPrinted]
where DocumentNo='0000027084'  and ProductionPlanItemID='5865406'
GROUP BY 
      [ProductionPlanItemID]
      ,[UserName]
      ,[ProductionPlanId]
      ,[QtyCompleted]
      ,[SubAssembledQty]
      ,[QtyRequired]
      , [CompletedPrintedId]
      ,[SOPOrderReturnLineId]

Схема Colum:

CREATE TABLE [dbo].[CompletedPrinted](
    [CompletedPrintedId] [bigint] NOT NULL,
    [UserName] [nvarchar](66) NOT NULL DEFAULT (''),
    [StartDateTIme] [datetime] NULL,
    [EndDateTime] [datetime] NULL,
    [ProductionPlanId] [bigint] NOT NULL DEFAULT ((0)),
    [SopLineItemId] [nvarchar](64) NOT NULL DEFAULT (''),
    [Detail] [nvarchar](1002) NOT NULL DEFAULT (''),
    [isActive] [bit] NOT NULL DEFAULT ((0)),
    [DocumentNo] [nvarchar](102) NOT NULL DEFAULT (''),
    [StockCode] [nvarchar](32) NOT NULL DEFAULT (''),
    [StockDescription] [text] NOT NULL DEFAULT (''),
    [QtyCompleted] [bigint] NOT NULL DEFAULT ((0)),
    [SubAssembledQty] [bigint] NOT NULL DEFAULT ((0)),
    [QtyRequired] [bigint] NOT NULL DEFAULT ((0)),
    [ProductionPlanItemID] [bigint] NOT NULL DEFAULT ((0)),
    [SOPOrderReturnLineId] [bigint] NOT NULL DEFAULT ((0))
)

Я создал скрипту sql ниже с примерами данных.

http://sqlfiddle.com/#!18/8927c/2

enter image description here

Редактировать 2 Извините, я должен был заявить, что мне нужны другие столбцы.

Ответы [ 2 ]

1 голос
/ 13 марта 2019

используйте row_number (), если вам нужна одна строка для ProductionPlanId

select * from (SELECT [CompletedPrintedId]
      ,[UserName]
      ,[ProductionPlanId]
      ,[QtyCompleted]
      ,[SubAssembledQty]
      ,[QtyRequired]
      ,[ProductionPlanItemID]
      ,[SOPOrderReturnLineId]
      ,row_number() over(partition by ProductionPlanId
                          order by QtyCompleted) rn
  FROM [CompletedPrinted]
  where DocumentNo='0000027084'  and ProductionPlanItemID='5865406'
) a where a.rn=1

демонстрационная ссылка

но, похоже, вам просто нужно sum()

select    
      [ProductionPlanId]
      ,sum(QtyCompleted) 

  FROM [CompletedPrinted]
  where DocumentNo='0000027084'  and ProductionPlanItemID='5865406'
  group by ProductionPlanId

выход

 ProductionPlanId   QtyCompleted
  5865405             3

, так как вам нужен также весь столбец, поэтому попробуйте ниже

/ ****** Скрипт для команды SelectTopNRows из SSMS ****** /

 with cte as
  ( select    
     c.ProductionPlanId
      ,sum(QtyCompleted)  as QtyCompleted

  FROM [CompletedPrinted] c
  where DocumentNo='0000027084'  and ProductionPlanItemID='5865406'
  group by ProductionPlanId
    ) , cte2 as
    (select cte.QtyCompleted as MQtyCompleted,c2.*,
       row_number()over(partition by c2.ProductionPlanId order by cte.QtyCompleted) rn
       from
    cte join CompletedPrinted c2
    on cte.ProductionPlanId=c2.ProductionPlanId
     ) select * from cte2 where rn=1
0 голосов
/ 13 марта 2019

Исключить все столбцы, кроме ProductionPlanId в GROUP BY предложении и выполнить агрегирование:

SELECT [ProductionPlanId], SUM([QtyCompleted])
FROM [CompletedPrinted]
WHERE DocumentNo = '0000027084' AND ProductionPlanItemID='5865406'
GROUP BY [ProductionPlanId];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...