【发布时间】:2016-07-22 03:07:49
【问题描述】:
在我的销售表中,列出的是某一物业中特定租户的每日销售额。
使用此代码,我能够列出或选择租户的每日销售额,根据物业分组进行汇总。
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 日期作为第一行,将 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,那就更好了。
希望得到您的专家建议。
谢谢!
【问题讨论】:
标签: sql sql-server sql-server-2008 tsql stored-procedures