如何在SQL中将行转换为列?

时间:2013-05-22 11:49:47

标签: asp.net sql

实际上我有一个查询,它在单行中为每个或它们返回5列和值(日期),但我想要的是列名称应该在单个列Title及其(Vale)中Date中的第二列。

注意TitleDate是我刚刚创建的临时表的列。

这是我正在使用的代码,

protected void btnAlerts_Click(object sender, EventArgs e)
{
       fnSaveAlerts();
}

private void fnSaveAlerts()
{
    DataTable dtTemp = new DataTable();

    DataColumn dtC1 = new DataColumn();
    dtC1.DataType = typeof(String);
    dtC1.ColumnName = "Title";

    DataColumn dtc2 = new DataColumn();
    dtc2.DataType = typeof(DateTime);
    dtC1.ColumnName = "Date";

    dtTemp.Columns.Add(dtC1);
    dtTemp.Columns.Add(dtc2);

    LeadsContracts ObjLeadsContract = new LeadsContracts();

    ObjLeadsContract.ExecuteSql(@"select dtDisclosure, dtDueDiligence, 
                                         dtFinanceAppraisals, dtFreeTextDate1, 
                                         dtFreeTextDate2 
                                  from LeadsContracts 
                                  where dtDisclosure is not null 
                                    and dtDueDiligence is not null 
                                    and dtFinanceAppraisals is not null 
                                    and dtFreeTextDate1 is not null 
                                    and dtFreeTextDate2 is not null");

    dtTemp.DataSet = ObjLeadsContract.DefaultView;  // it also gives error here "Red line"

}

我已经花了一整天的时间来做这件事,请任何人都可以帮助我。提前谢谢

2 个答案:

答案 0 :(得分:0)

我会给你一些解决方案的提示:
对于您的问题,您可以使用二维数组。

[0] [“Title”,DatabaseValue]
[1] [“Date”,DatabaseValue]
[2] [
[3] [
[4] [

因此,首先循环查询的五个值并填入二维数组

[0] [1]
[1] [1]
[2] [1]
[3] [1]
[4] [1]

然后你可以循环输出二维数组...

答案 1 :(得分:0)

你期待这样的事吗?

DECLARE @Temp AS TABLE (dtDisclosure varchar(20),dtDueDiligence varchar(20),dtFinanceAppraisals varchar(20),dtFreeTextDate1 varchar(20),dtFreeTextDate2 varchar(20))
INSERT INTO @Temp VALUES ('20-Apr-2013','20-Apr-2013','20-Apr-2013','20-Apr-2013','20-Apr-2013'),
                        ('21-Apr-2013','21-Apr-2013','21-Apr-2013','21-Apr-2013','21-Apr-2013')

SELECT [Title],[Date] FROM
(
   SELECT * FROM @temp
} A
UNPIVOT
{
    [Date] FOR [Title] IN     IN ([dtDisclosure],[dtDueDiligence],[dtFinanceAppraisals],[dtFreeTextDate1],[dtFreeTextDate2])
} AS Unpvt;

输出:

Title                 Date
dtDisclosure          20-Apr-2013
dtDueDiligence        20-Apr-2013
dtFinanceAppraisals   20-Apr-2013
dtFreeTextDate1       20-Apr-2013
dtFreeTextDate2       20-Apr-2013
dtDisclosure          21-Apr-2013
dtDueDiligence        21-Apr-2013
dtFinanceAppraisals   21-Apr-2013
dtFreeTextDate1       21-Apr-2013
dtFreeTextDate2       21-Apr-2013