简体   繁体   English

SQL Server 2008:如何根据两个条件求和?

[英]SQL Server 2008: How do you SUM based on two conditions?

If I work at a grocery store and need to make orders for inventory, we make orders multiple times a month rather than one large order.如果我在杂货店工作并且需要为库存下订单,我们每个月都会下多次订单,而不是一个大订单。

Item物品 ETA预计到达时间 QTY数量
Apples苹果 5/6/21 21 年 5 月 6 日 10 10
Apples苹果 6/12/21 21 年 6 月 12 日 15 15
Apples苹果 6/30/21 21 年 6 月 30 日 10 10
Bananas香蕉 6/12/21 21 年 6 月 12 日 15 15
Bananas香蕉 7/5/21 21 年 7 月 5 日 20 20
Cereal谷物 5/15/21 21 年 5 月 15 日 10 10
Cereal谷物 5/30/21 21 年 5 月 30 日 50 50
Cereal谷物 7/15/21 21 年 7 月 15 日 20 20

Is there a way to create a table that sums the QTY, if the item is the same and if the ETA month is the same to know how much of each Item is expected to arrive in a given month?有没有办法创建一个汇总 QTY 的表格,如果项目相同并且 ETA 月份是否相同,以了解每个项目在给定月份预计会到达多少?

Ideally, the result I'm looking for is something that looks like this理想情况下,我正在寻找的结果是这样的

Item物品 May可能 June六月 July七月
Apples苹果 10 10 25 25 0 0
Bananas香蕉 0 0 15 15 20 20
Cereal谷物 60 60 0 0 20 20

I would need the code to first check to see what month the item is expected to arrive in, and then if there are more than one lines that have the same item and ETA month, SUM the QTY.我需要代码首先检查该项目预计到达的月份,然后如果有多个行具有相同的项目和 ETA 月份,则对数量求和。

I have tried doing CASE WHEN statements but always end up with syntax errors我试过做 CASE WHEN 语句,但总是以语法错误结束

SELECT 
    CASE WHEN ETA BETWEEN '2021-05-01' AND '2021-05-31'
    AND WHERE Item IN 
        (SELECT Item 
        FROM ['Inventory'] 
        GROUP BY Item HAVING COUNT(*)>1)
        THEN SUM(QTY)
    END AS MAY_QTY
        
FROM [dbo].['Inventory'];

You just use conditional aggregation:您只需使用条件聚合:

select item,
       sum(case when month(eta) = 5 then qty else 0 end) as may,
       sum(case when month(eta) = 6 then qty else 0 end) as jun,
       sum(case when month(eta) = 7 then qty else 0 end) as jul
from inventory i
group by item;

I would caution you that using months without a year may lead to problems.我会提醒你,使用没有一年的月份可能会导致问题。 That is also true of using unsupported software -- SQL Server 2008 is no longer supported.使用不受支持的软件也是如此——不再支持 SQL Server 2008。

First you should group the data by item and month, and then use pivot to convert rows to columns.首先您应该按项目和月份对数据进行分组,然后使用 pivot 将行转换为列。

select
    item, 
    isnull(may,0) as May, 
    isnull(june,0) as June, 
    isnull(july,0) as July
from
(
  select item, datename(month, ETA) as _month, sum(qty) as qty
  from Inventory
  group by item, datename(month, ETA)
) d
pivot
(
  sum(qty)
  for _month in (may, june, july)
) piv;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM