好的,我有一段时间没有做过SQL。这是我必须得到的最深入的。基本上我有一个转动表,然后根据日期分解它。
现在我有一个经历的交易。有3种交易类型。让我们说交付,运送,返回。所以我的表有一个交易ID,交易日期和交易类型。我需要对此进行透视并计算然后对事务类型求和。到目前为止我有这个代码:
SELECT
SUM(Delivered),
SUM(Shipped),
SUM(Returned),
TransactionID,
TransactionDate
FROM
(
(SELECT
TransactionID,
TransactionDate,
TransactionType
FROM Transactions) AS Ttable
PIVOT
(
COUNT(TransactionType)
FOR TransactionTYpe IN
(
[Delivered],
[Shipped],
[Returned]
)
) as Pvt1
)
这获取每种交易类型的计数总和。但是,这为我提供了所有现有交易类型的总计。我需要在一段时间内完成所有这些工作。例如(我知道这将是很多变量,但它是我的应用程序可以做到的唯一方式),我需要找出每个月的2010年1月 - 2012年12月所有交易类型的总和。所以12x3。我怎么能这样打破这个?请帮忙!疯了!
答案 0 :(得分:1)
这是一个起点:
SELECT TransactionMonth, [Delivered], [Shipped], [Returned]
from (select
TransactionType
,cast(datename(mm, TransactionDate) + ' 1, ' + datename(yy, TransactionDate) as smalldatetime) TransactionMonth
from Transactions) ByMonth
pivot (count(ByMonth.TransactionType)
for ByMonth.TransactionType in ([Delivered],[Shipped],[Returned] )
) xx
order by TransactionMonth
目前还不完全清楚源数据是什么样的,或者你的最终网格应该是什么,所以我做了一些假设: