在我的销售表中,列出了一个物业中特定租户的每日销售额。
使用此代码,我能够列出或选择租户的每日销售额,根据物业分组进行总结。
SELECT date , location , SUM(a.gsc) Sales
FROM SalesTable
WHERE (date BETWEEN '01/01/2015' AND '12/31/2015' )
and (location = 'Property1')
GROUP BY location , date
ORDER BY location, date
结果是这样的
Date Location Sales
01/01/2015 Property1 10,000
01/02/2015 Property1 20,000
.
.
.
12/31/2015 Property1 15,000
我希望完成的最终输出是以表格形式生成结果,其中Days days作为第一行和Month作为列。 请参阅示例输出以进一步说明。
Date January February
Date Day Sales Date Day Sales
1 1-Jan Fri 10,000 1-Feb Mon 9,000
2 2-Jan Sat 20,000 2-Feb Tue 10,000
3 . . . . . .
4 . . . . . .
5 . . . . . .
6
7
8
.
.
.
.
.
31
这是我试过的
SELECT date , location , SUM(a.gsc) Sales
INTO #TempTable1
FROM SalesTable
WHERE (date BETWEEN '01/01/2015' AND '12/31/2015' )
and (location = 'Property1')
GROUP BY location , date
ORDER BY location, date
SELECT months.number, tenants.locationd , tenants.location
,(case when (t.DATE) = 1 then t.gsc end) as 'January'
,(case when (t.DATE) = 2 then t.gsc end)) as 'February'
(case when year(t.DATE) = 3 then t.gsc end) as 'March'
FROM
(
SELECT Number
FROM master..spt_values
WHERE Type = 'P' and Number between 1 and 31
) months
CROSS JOIN
( --12 Month Name will be cross joined sa selected tenant/s
SELECT DISTINCT locationd , location
FROM #AMRDSR1
) tenants
LEFT JOIN #AMRDSR1 t
ON months.number = datepart(day,t.date) and tenants.location = t.location
GROUP BY months.number, tenants.locationd , tenants.location , t.date, t.gsc
ORDER BY tenants.locationd , datepart(day,t.date)
我被建议使用pivot,但这对我来说很新,而且似乎非常复杂,如果有办法只使用TSQL,那就更好了。
希望获得专家意见。
谢谢!
答案 0 :(得分:1)
-- assuming you only show one year of data at a time
; with
-- first get sales by date and the day of month and also month etc.
data
(
SELECT [date] , SUM(a.gsc) AS Sales,
datepart(day, [date]) as [Day],
datepart(month, [date]) as [Month],
left(datename(weekday, [date]),3) as [WeekDay]
FROM SalesTable a
WHERE ([date] BETWEEN '01/01/2015' AND '12/31/2015' )
and (location = 'Property1')
GROUP BY [date]
)
-- Now the "pivoting" using CASE WHEN .... with aggregate function
SELECT [Day],
MAX(CASE WHEN [Month] = 1 THEN [date] END) as Date_Jan,
MAX(CASE WHEN [Month] = 1 THEN [WeekDay] END) as WeekDay_Jan,
SUM(CASE WHEN [Month] = 1 THEN [Sales] END) as Sales_Jan,
MAX(CASE WHEN [Month] = 2 THEN [date] END) as Date_Feb,
MAX(CASE WHEN [Month] = 2 THEN [WeekDay] END) as WeekDay_Feb,
SUM(CASE WHEN [Month] = 2 THEN [Sales] END) as Sales_Feb,
. . . .
FROM data
GROUP BY [Day]