0
 Table - T1 (id, Description)
 Table - T2 (id, fk_id,Dates, Amount)

select d.Description,dt.Dates,dt.Amount
 from T2 as dt join T1 d
  on
 d.id = dt.fk_id
group by d.Description,dt.Dates,dt.Amount

在上面运行查询结果显示如下

Description       Dates           Amount
nutrition1      2012-01-01      100.00
nutrition1      2013-01-01      100.00
nutrition2      2012-01-01      100.00
nutrition2      2013-01-01      600.00
nutrition3      2012-01-01      300.00
nutrition3      2013-01-01      700.00
nutrition4      2012-01-01      400.00
nutrition4      2013-01-01      800.00
nutrition5      2012-01-01      300.00
nutrition5      2013-01-01      600.00

我想将结果显示为

Description    01-01-2012  01-01-2013
nutrition1       100          100
nutrition2       100          600
nutrition3       300          700
nutrition4       400          800
nutrition5       300          600

日期会改变

4

2 回答 2

2

这种类型的转换是PIVOT. 如果您提前知道这些值,则可以对它们进行类似于以下的硬编码:

select *
from
(
  select d.Description,convert(char(10), dt.dates, 110) dates,dt.Amount
  from T2 as dt 
  join T1 d
    on d.id = dt.fk_id
) src
pivot
(
  sum(amount)
  for dates in ([01-01-2012], [01-01-2013])
) piv

请参阅带有演示的 SQL Fiddle

如果您有未知的值要转换,那么您将需要使用动态 sql:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(char(10), dates, 110)) 
                    from T2
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Description, ' + @cols + ' from 
             (
                select d.Description,convert(char(10), dt.dates, 110) dates,dt.Amount
                from T2 as dt 
                join T1 d
                  on d.id = dt.fk_id
            ) x
            pivot 
            (
                sum(amount)
                for dates in (' + @cols + ')
            ) p '

execute(@query)

请参阅带有演示的 SQL Fiddle

两个版本产生相同的结果:

| DESCRIPTION | 01-01-2012 | 01-01-2013 |
-----------------------------------------
|  nutrition1 |        100 |        100 |
|  nutrition2 |        100 |        600 |
|  nutrition3 |        300 |        700 |
|  nutrition4 |        400 |        800 |
|  nutrition5 |        300 |        600 |
于 2013-01-04T12:00:39.870 回答
0
SELECT Description,
  SUM(
  CASE
    WHEN dt.Dates=to_date('01-01-2012','dd-mm-yyyy')
    THEN dt.Amount
    ELSE 0
  END) AS '01-01-2012' ,
  SUM(
  CASE
    WHEN dt.Dates=to_date('01-01-2013','dd-mm-yyyy')
    THEN dt.Amount
    ELSE 0
  END) '01-01-2013'
FROM T2 AS dt
JOIN T1 d
ON d.id = dt.fk_id
GROUP BY d.Description;
于 2013-01-04T11:53:42.440 回答