我无法加载该表。我希望所有<500的数量值加总,其中NameCode相同。如果总和仍然小于500,请不要插入。这可能吗?
CREATE TABLE [dbo].[GovQuantity](
[NameCode] [varchar](40) NULL,
[Quantity] [decimal](18,6) NULL,
)
INSERT INTO GovQuantity
SELECT d.NumNameCode
, Quantity = CASE WHEN QUANTITY < 500 THEN SUM(Quantity) ELSE Quantity END
FROM [...]
GROUP BY NumNameCode, Quantity
当前拥有这个:
NameCode Quantity
ArmyGuard 125
ArmyGuard 605
ArmyGuard 65
Boeing 420
Boeing 750
Boeing 100
需要:
NameCode Quantity
ArmyGuard 605
Boeing 520
Boeing 750
答案 0 :(得分:1)
也许是这样的。
这将显示> = 500的各个行并汇总其他杂项。其他人。
示例
;with cte as (
Select NameCode
,Quantity
,RN = Row_Number() over (Partition By NameCode Order by Quantity)
From [dbo].[GovQuantity]
)
Select NameCode
,Quantity = sum(Quantity)
From cte
Group By NameCode,case when Quantity >=500 then RN else 0 end
Having sum(Quantity) > 500
Order by NameCode
返回
NameCode Quantity
ArmyGuard 605
Boeing 520
Boeing 750
答案 1 :(得分:0)
您可以尝试一下。
DECLARE @T TABLE (NameCode VARCHAR(10), Quantity INT)
INSERT INTO @T VALUES
('ArmyGuard', 125),
('ArmyGuard', 605),
('ArmyGuard', 65 ),
('Boeing ', 420),
('Boeing ', 750),
('Boeing ', 100)
SELECT NameCode, SUM(Quantity) Quantity FROM @T
GROUP BY
NameCode,
(CASE WHEN Quantity < 500 THEN 0 ELSE Quantity END)
HAVING
SUM(Quantity) >= 500
ORDER BY
NameCode
结果:
NameCode Quantity
---------- -----------
ArmyGuard 605
Boeing 520
Boeing 750
答案 2 :(得分:0)
您似乎想要union all
:
select NumNameCode, sum(Quantity) as Quantity
from table t
where Quantity < 500
group by NumNameCode
union all
select NumNameCode, Quantity
from table t
where Quantity >= 500;
答案 3 :(得分:0)
最安全的写法是使用union all
:
select NameCode, sum(Quantity) as Quantity
from govquantity
where Quantity < 500
group by NameCode
having sum(Quantity) >= 500
union all
select NameCode, Quantity
from govquantity
where Quantity >= 500;
使用单个聚合写这个很诱人:
我想你只是想要
SELECT d.NumNameCode, SUM(Quantity)
FROM [...]
WHERE QUANTITY < 500
GROUP BY NumNameCode,
(CASE WHEN Quantity >= 500 THEN Quantity END)
HAVING SUM(QUANTITY) >= 500;
但是,如果两个quantity
值相同且大于500,则会造成混乱。
如果您有一个唯一的ID(或每个名称至少一个唯一),则为:
SELECT d.NumNameCode, SUM(Quantity)
FROM [...]
WHERE QUANTITY < 500
GROUP BY NumNameCode,
(CASE WHEN Quantity >= 500 THEN Id END)
HAVING SUM(QUANTITY) >= 500;