如何根据以下格式获取数据:
Id name year month amount
1 A 2012 jan 100
1 A 2012 jan 900
1 A 2012 jan 300
1 A 2012 apr 100
1 A 2012 apr 500
2 B 2013 may 100
输出将采用下面提到的形式,如果参数中的名称,年份和月份,
Id name Jan feb mar Apr may jun ...... jan .....may total
1 A 1300 0 0 600 0 0 ..... 0 ...... 0 1900
2 B 0 0 0 0 0 0.........0.......100 100
答案 0 :(得分:0)
您需要使用PIVOT
来获得您提到的结果
以下是使用PIVOT
和你的sql syntex一样
SELECT * FROM (SELECT t.id,t.name,t.month,t.amount,(SELECT SUM(t2.amount) FROM dbo.test AS t2 GROUP BY t2.name HAVING t2.name= t.name ) AS total FROM dbo.test AS t) as s
PIVOT
(
SUM(Amount)
FOR [month] IN (jan, feb, mar, apr,
may, jun, jul, aug, sep, oct, nov, dec)
)AS pivots
答案 1 :(得分:0)
declare @t table (Id INT,name VARCHAR(10),years VARCHAR(10),months VARCHAR(10),amt INT )
insert into @t (Id,name,years,months,amt)values (1,'A','2012','jan',100)
insert into @t (Id,name,years,months,amt)values (2,'A','2012','jan',100)
insert into @t (Id,name,years,months,amt)values (3,'A','2012','apr',200)
insert into @t (Id,name,years,months,amt)values (4,'A','2012','apr',100)
insert into @t (Id,name,years,months,amt)values (5,'B','2013','may',200)
Select id,
name,
ISNULL(jan,0) As Jan,
ISNULL(feb,0) As FEb,
ISNULL(mar,0) As Mar,
ISNULL(apr,0)As Apr,ISNULL(JUn,0)As Jun,ISNULL(jul,0)As jul,ISNULL(aug,0)As aug
from
(Select distinct t.ID,t.name,t.years,t.months As Months,t.amt
from @t t)t
PIVOT (SUM(amt)FOR Months IN( [jan],
[feb],
[mar],
[apr],[JUn],[jul],[aug]))p
答案 2 :(得分:0)
我认为这可能需要一个动态的支点?
CREATE TABLE #Data (
Id INT,
name VARCHAR(1),
[year] INT,
[month] VARCHAR(3),
amount INT);
INSERT INTO #Data VALUES (1, 'A', 2012, 'jan', 100);
INSERT INTO #Data VALUES (1, 'A', 2012, 'jan', 900);
INSERT INTO #Data VALUES (1, 'A', 2012, 'jan', 300);
INSERT INTO #Data VALUES (1, 'A', 2012, 'apr', 100);
INSERT INTO #Data VALUES (1, 'A', 2012, 'apr', 500);
INSERT INTO #Data VALUES (2, 'B', 2013, 'may', 100);
DECLARE @cols VARCHAR(1024);
SELECT
@Cols = STUFF((
SELECT DISTINCT
',' + QUOTENAME(CONVERT(VARCHAR(4), [year]) + '/' + [month])
FROM
#Data
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1 ,1 ,'');
DECLARE @Query VARCHAR(MAX);
SELECT @Query = '
WITH Aggregated AS (
SELECT
Id,
name,
CONVERT(VARCHAR(4), [year]) + ''/'' + [month] AS YearMonth,
SUM(amount) AS amount
FROM
#Data
GROUP BY
Id,
name,
[year],
[month])
SELECT
*
FROM
Aggregated
PIVOT (
SUM(amount)
FOR YearMonth IN (' + @cols + ')
) p;';
EXEC (@Query);
结果如下:
Id name 2012/apr 2012/jan 2013/may
1 A 600 1300 NULL
2 B NULL NULL 100