美好的一天!我正在制作一个图表,我需要显示本周的所有日子以显示每周的销售额。到目前为止,我能够显示本周的所有日子,我只是在显示每周的每一天的销售时遇到了麻烦。由于数据库中没有记录一周的日子,所以TOTAL_SALES列应该都返回Null值。相反,它返回数据库中记录的总销售额。到目前为止,这是我的存储过程查询。
WITH DAYSOFTHEWEEK AS
(
SELECT 0 DAY
UNION ALL
SELECT DAY + 1 FROM DAYSOFTHEWEEK WHERE DAY < 6
)
SELECT DATEADD(DAY, DAY, DATEADD(DAY, 2-DATEPART(WEEKDAY, CONVERT (date, GETDATE())), CONVERT (date, GETDATE()))) AS DAY_OF_THE_WEEK,
SUM([ORDER].NET_AMOUNT) AS TOTAL_SALES
FROM DAYSOFTHEWEEK, [ORDER]
GROUP BY DAYSOFTHEWEEK.DAY
我尝试添加此条件语句
WHERE DAYSOFTHEWEEK.DAY IN ([ORDER].ORDER_DATE)
但它会返回此错误
Operand type clash: date is incompatible with int
有人可以帮我解决这个问题吗?有没有解决过我已有的代码?提前谢谢!
答案 0 :(得分:1)
如果没有销售,我认为您之后的SUM
是当天每天NULL
-- Setup some fake sales data
WITH TestData(N, Order_Date, Net_Amount) AS (
SELECT 1 N, CAST(GETDATE() AS DATE) Order_Date, RAND() * 100 Net_Amount
UNION ALL
SELECT N+1 N, CAST(GETDATE()-N/5 AS DATE) Order_Date, RAND(CHECKSUM(NEWID())) * 100 Net_Amount FROM TestData
WHERE N < 20
)
SELECT TestData.Order_Date, TestData.Net_Amount INTO #Order FROM TestData
--Set the first day of the week (if required)
SET DATEFIRST 7 --Sunday
;WITH Days(N,DayOfTheWeek) AS (
SELECT 1 N, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE,GETDATE())) DayOfTheWeek
UNION ALL
SELECT N+1 N,DATEADD(DAY, 1, DayOfTheWeek) DayOfTheWeek FROM Days
WHERE N < 7
)
SELECT d.DayOfTheWeek, SUM(Net_Amount) TotalAmount
FROM Days d
LEFT JOIN #Order ON d.DayOfTheWeek = Order_Date
GROUP BY d.DayOfTheWeek
DayOfTheWeek TotalAmount
------------ ----------------------
2016-08-07 219.036784917497
2016-08-08 273.319570812461
2016-08-09 271.148114731087
2016-08-10 194.780039228967
2016-08-11 NULL
2016-08-12 NULL
2016-08-13 NULL
的{{1}}。秘诀是将您的日期列表添加到您的数据中:
[[NSUserDefaults standarUserDefaults] setValue:@"en"] forKey:@"AppleLanguages"];
[[NSUserDefaults standarUserDefaults] synchronize];
答案 1 :(得分:0)
对我来说有点复杂: 获取周使用的名称,例如
SELECT DATENAME(dw,getdate())
但你确实需要这样的东西:
SELECT ProductName,Sum(Sales) From NameOfTable GROUP BY
DATENAME(ww,salesDate)
答案 2 :(得分:0)
本周的每一天,从您的日期第一个日期开始,如果您需要其他一周的开始日期,可以使用SET DATEFIRST临时更改查询
我认为你在那里有一些销售表,你还没有向我们展示,你需要加入到那个日期,然后分组
WITH DAYSOFTHEWEEK AS
(
SELECT cast(dateadd(
day,
-datepart(weekday,getdate()) + 1 ,
GETDATE()
)
as date) [DAY], 0 as cnt
UNION ALL
SELECT dateadd(day,1,[DAY]), cnt + 1 FROM DAYSOFTHEWEEK WHERE cnt < 6
)
select DAYSOFTHEWEEK.[day], SUM([ORDER].NET_AMOUNT) AS TOTAL_SALES from daysoftheweek
JOIN
SalesTable on
CAST(SalesTable.SalesDate date) = DAYSOFTHEWEEK.[day]
GROUP BY DAYSOFTHEWEEK.[day]