选择行到列SQL

时间:2015-08-04 03:49:20

标签: sql sql-server

之前我没有遇到过一行一栏,你能帮助我吗?

这是我的来源的例子。

我想选择:

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
{
    // set this at design-time, or at least
    // in the Form's constructor. It does not
    // belong here...
    //Edit1->MaxLength = 6;

    if( Key == VK_BACK )
        return;

    if( (Key < L'0') || (Key > L'9') )
    {
        ShowMessage("Please enter numerals only");
        Key = 0;
    }
}

Id  Project ID  Date      Hour
-------------------------------
1   Project-1   1/1/2010    10
2   Project-1   1/2/2010     2
3   Project-1   1/3/2010     3
4   Project-1   1/4/2010     5
5   Project-2   1/1/2010     3
6   Project-2   1/2/2010     4
7   Project-2   1/3/2010     2
8   Project-2   1/4/2010     7
9   Project-3   1/1/2010     5
10  Project-3   1/2/2010     6
11  Project-3   1/3/2010     4
.
.
.

请帮帮我。

更新

这是我的解决方案。

Project ID  1/1/2010    1/2/2010    1/3/2010    1/4/2010    ...
----------------------------------------------------------------
Project-1     10          2            3           5
Project-2     3           4            2           7
Project-3     5           6            4    

希望它能帮助别人。

1 个答案:

答案 0 :(得分:4)

静态解决方案正在使用此类查询:

SELECT
    ProjectID,
    SUM(CASE WHEN Date = '1/1/2010' THEN Hour ELSE 0 END) As '1/1/2010',
    SUM(CASE WHEN Date = '1/2/2010' THEN Hour ELSE 0 END) As '1/2/2010',
    SUM(CASE WHEN Date = '1/3/2010' THEN Hour ELSE 0 END) As '1/3/2010',
    SUM(CASE WHEN Date = '1/4/2010' THEN Hour ELSE 0 END) As '1/4/2010',
    ...
FROM
    yourTable
GROUP BY
    ProjectID;

要使用动态解决方案,您需要使用动态SQL,如下所示:

Declare @SQL nvarchar(MAX)

SELECT @SQL = ISNULL(@SQL, 'SELECT ProjectID') + ', SUM(CASE WHEN Date = ''' + [Date] + ''' THEN [Hour] ELSE 0 END) As [' + [Date] + ']'
FROM @t
GROUP BY [Date]

SELECT @SQL = @SQL + ' FROM yourTable GROUP BY ProjectID;'

EXEC(@SQL)