1

我正在尝试根据每月输入日期选择项目总和:

库存表如下:

    EntryDate    Items

    1/1/2013      2
    1/20/2013     5
    1/23/2013     3
    1/30/2013     2
    2/4/2013      4
    2/17/2013     34 

添加了 Total 行的所需输出:

    EntryDate    Items

    1/1/2013        2
    1/20/2013       5
    1/23/2013       3
    1/30/2013       2
    **Total         12**
    2/4/2013        4
    2/17/2013       34 
    **Total         38**

下面是我的尝试。我正在尝试使用汇总来做到这一点,但它一次计算所有项目而不是按月计算,如何实现这一点:

Select Convert(date, EntryDate) AS [DATE],SUM(Items) AS Total, 
Case WHEN GROUPING(Items) = 1 THEN 'Rollup'
Else Status end AS Total From [Inventory]  Group by Convert(date, EntryDate) WITH 
Rollup
4

5 回答 5

4

如果你真的想要像你的例子一样的结果,你可以使用以下内容:

SELECT EntryDate, Items
FROM (SELECT YEAR(EntryDate)'Year_',MONTH(EntryDate)'Month_',CAST(EntryDate AS VARCHAR(12))'EntryDate',Items,1 'sort'
      FROM Inventory
      UNION ALL
      SELECT YEAR(EntryDate)'Year_',MONTH(EntryDate)'Month_','Total',SUM(Items)'Items',2 'sort'
      FROM Inventory
      GROUP BY YEAR(EntryDate),MONTH(EntryDate)
      )sub
ORDER BY Year_,Month_,sort

演示: SQL 小提琴

于 2013-07-05T10:51:22.493 回答
1

试试这个,它会在一个新列中为您提供月份总数,当您的日期超过 1 年时它也可以工作

SELECT EntryDate, Items, 
SUM(Items) OVER (partition by dateadd(month, datediff(month, 0, entrydate), 0)) Total 
FROM [Inventory]

结果:

EntryDate   Items   Total
2013-01-01  2       12
2013-01-20  5       12
2013-01-23  3       12
2013-01-30  2       12
2013-02-04  4       38
2013-02-17  34      38
于 2013-07-05T10:50:54.283 回答
0

DATEPART会试试这个,

SELECT DATEPART(month, EntryDate) AS 'Month Number',sum(items1) FROM ITEMS
GROUP BY DATEPART(month, EntryDate)

# sqlfiddle

于 2013-07-05T10:32:17.137 回答
0

这里有适合您的完美解决方案

select isnull(cast(DATEFROMPARTS(year,month,day) as varchar),'Total'), 
       items 
  from (  SELECT datepart(yyyy,EntryDate) year,
                 DATEPART(mm, EntryDate) month, 
                 DATEPART(dd, EntryDate) day,
                 sum(items) items
            From Inventory 
        GROUP BY 
          ROLLUP (datepart(yyyy,EntryDate),
                  DATEPART(mm, EntryDate), 
                  DATEPART(dd, EntryDate) 
                 )
       ) a
 where a.year is not null
   and a.month is not null;

在这里演示

于 2013-07-05T10:35:38.590 回答
0

尝试:

 select entryDate, Items, sum(Items) 
     from (select entryDate,Items, to_date(entry_date, 'mm/yyyy') month_date from Inventory) 
     group by month_date
于 2013-07-05T10:45:26.953 回答