销售的个别商品的销售额按周计算

时间:2014-12-31 11:07:12

标签: sql count sales

我有一个大型SQL表,其中包含以下

等字段
Item,              Date Sold,
1 Day Coaster      2014-11-10,
3 Day Coaster      2014-02-16,
1 Day Coaster      2014-11-11,
AC-Zip             2014-12-21,
5 Day Package      2014-05-15,
1 Day Coaster      2014-11-07,

作为SQL的新手,我的专业知识只能单独选择项目并从单个结果中获取计数,并从受影响的行中键入excel。

我需要能够按周计算出售的单个商品的数量,并将按周列出的数量列入excel电子表格中;

Week                          Item                   Count
2014-11-07-2014-11-13       1 Day Coaster            3

3 个答案:

答案 0 :(得分:0)

您需要使用Group BY语句。

这是一个示例SQLFiddle,它可能会帮助您入门:SQL Fiddle

答案 1 :(得分:0)

您可以使用:

SELECT A.Item,A.DateRange,COUNT(A.Item) 
FROM (
SELECT Item,
(SELECT DISTINCT
    CASE 
        WHEN YEAR(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(Date_Sold)), Min(Date_Sold))) < YEAR(Min(Date_Sold))
        THEN
        CAST(DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0 ,GETDATE())), 0) AS Varchar(50))  
        + ' TO ' + Cast(DATEADD(dd, 7-(DATEPART(dw, Min(Date_Sold))), Min(Date_Sold))  AS Varchar(50))
        ELSE
        Cast(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(Date_Sold)), Min(Date_Sold)) AS Varchar(50)) 
        + ' TO ' +     Cast(DATEADD(dd, 7-(DATEPART(dw, Min(Date_Sold))), Min(Date_Sold))  AS Varchar(50))
    END AS  DateRange
FROM <YOUR_TABLE> B
WHERE A.Date_Sold=B.Date_Sold
AND A.Item=B.Item
group by Item
) AS DateRange
FROM <YOUR_TABLE> A
) A 
GROUP BY Item,DateRange;

请告诉我这不是您正在看的内容。

答案 2 :(得分:-1)

使用此。 Fiddler Demo

<强>输出:

enter image description here

<强>查询

CREATE TABLE weekdays
(
  datevalue datetime NOT NULL
  , Item VARCHAR(MAX)
  );

INSERT INTO weekdays (datevalue, item) VALUES
  ('2014-11-10', '1 Day Coaster'),
  ('2014-02-16', '2 Day Coaster'),
  ('2014-11-11', '1 Day Coaster'),
  ('2014-12-21', 'AC-Zip'),
  ('2014-05-15', '5 Day Package'),
  ('2014-11-07', '1 Day Coaster');


CREATE FUNCTION [dbo].[ufn_GetFirstDayOfWeek]
( @pInputDate    DATETIME )
RETURNS DATETIME
BEGIN

SET @pInputDate = CONVERT(VARCHAR(10), @pInputDate, 111)
RETURN DATEADD(DD, 1 - DATEPART(DW, @pInputDate),
               @pInputDate)

END
GO

SET DATEFIRST 5

SELECT CONVERT(VARCHAR(10), A.Date, 101) + ' - ' + 
        CONVERT(VARCHAR(10), DATEADD(d, 6, A.Date), 101) AS Week,
      A.Item, 
      COUNT(A.Item) AS COUNT FROM
(SELECT [dbo].ufn_GetFirstDayOfWeek(datevalue) AS Date, item FROM weekdays) AS A
GROUP BY A.Date, A.Item