您可以使用帶有靜態/動態數據透視的PIVOT
來做到這一點。下面是一個靜態的旋轉的例子:
create table #temp
(
[group] varchar(1),
createdate smalldatetime,
qty int
)
insert into #temp values ('A', '3/1/2012', 5)
insert into #temp values ('A', '2/1/2012', 1)
insert into #temp values ('A', '2/1/2012', 3)
insert into #temp values ('B', '2/1/2012', 4)
insert into #temp values ('A', '1/1/2012', 1)
select [group]
, total
, isnull([1/1/2012], 0) as '2012/1'
, isnull([2/1/2012], 0) as '2012/2'
, isnull([3/1/2012], 0) as '2012/3'
from
(
select t1.[group], t1.createdate, t1.qty, t2.total
from #temp t1
left join
(
select [group], sum(qty) as Total
from #temp
group by [group]
) t2
on t1.[group] = t2.[group]
) x
pivot
(
sum(qty)
for createdate in ([3/1/2012], [2/1/2012], [1/1/2012])
) p
order by [group]
drop table #temp
一個動態的支點有很多的資源:
Pivots with Dynamic Columns in SQL Server 2005
Using SQL Server 2005/2008 Pivot on Unknown Number of Columns (Dynamic Pivot)
搜索做會給你很多答案在動態樞軸上也是如此。
你需要對內部工作連接來實現這一目標,但是是有可能。作爲閱讀材料[加入SQL](http://www.w3schools.com/sql/sql_join_inner.asp)。 – 2012-04-03 16:36:50
看起來像你想要的一個樞紐,爲什麼你不在服務器端而不是應用端做到這一點? – Taryn 2012-04-03 16:37:08
沒時間在這裏寫一個完整的答案,但如果您使用SQL Server,解決方案是通過動態SQL數據透視表。這是一個很好的例子:http://stackoverflow.com/a/7182489/570191 – 2012-04-03 16:39:41