0

Есть следующая выборка:

 1. 2017-05-21  13:45:16    Indicator1  15
 2. 2017-05-21  13:45:16    Indicator2  13.8
 3. 2017-05-21  13:45:16    Indicator3 0
 4. 2017-05-21  13:45:16    Indicator4 -7.1
 5. 2017-05-21  13:45:16    Indicator5 0
 6. 2017-05-21  13:45:16    Indicator6 24.2
 7. 2017-05-21  13:45:16    Indicator7 0
 8. 2017-05-21  13:45:16    Indicator8 0
 9. 2017-05-21  13:45:16    Indicator9 0
 10. 2017-05-21 13:45:17    Indicator6 23.2
 11. 2017-05-21 13:45:17    Indicator2  14.1
 12. 2017-05-21 13:45:18    Indicator4  -6.4
 13. 2017-05-21 13:45:18    Indicator6 21.4
 14. 2017-05-21 13:45:19    Indicator6 22
 15. 2017-05-21 13:45:19    Indicator2  14.2
 16. 2017-05-21 13:45:19    Indicator4  -5.9

мне нужно экспортировать в excel эти данные и получить в следующем виде:

Date Time Ind1 Ind2 Ind3 Ind4 Ind5 Ind6 Ind7 Ind8 Ind9

2017-05-21 13:45:16 15 13.8 0 -7.1 0 24.2 0 0 0
2017-05-21 13:45:17 15 14.1 0 -7.1 0 23.2 0 0 0
2017-05-21 13:45:18 15 14.1 0 -6.4 0 21.4 0 0 0
2017-05-21 13:45:19 15 14.2 0 -5.9 0 22 0 0 0
using (SqlDataReader reader = cmd.ExecuteReader())
{
    Row newRow = new Row();
    while (reader.Read())
    {   
        if (reader[1].ToString() != firstTime)
        {
            firstTime = reader[1].ToString();
            newRow.AppendChild(new Cell { DataType = CellValues.String, CellValue = new CellValue(reader[0].ToString()) });
            newRow.AppendChild(new Cell { DataType = CellValues.String, CellValue = new CellValue(firstTime) });
            newRow.AppendChild(new Cell { DataType = CellValues.String, CellValue = new CellValue(reader[3].ToString()) });
        }
        else
        {
            newRow.AppendChild(new Cell { DataType = CellValues.String, CellValue = new CellValue(reader[3].ToString()) });
        }                                            

    }sheetData.Append(newRow);    
}
1
  • переведите, пожалуйста, текст вопроса (нажав править ниже текста вопроса) на русский язык 21 мая 2017 в 14:07

1 ответ 1

0

Вы так и не написали, с чем вам надо разобраться. Возможно, вы хотите менять структуру с помощью Excel, тут я вам не помогу, но мне интересно было решить задачу чистым T-SQL.

Задача тут разбивается на две части:

  1. поскольку значение индикатора у вас переносится на следующее время, если не задано явно, нужно сначала заполнить пропуски. Делаем это с помощью скрипта от Itzik Ben-Gan
  2. Получив сплошную выборку, нужно заменить формат вывода, используя PIVOT.

итоговый скрипт получился таким:

--Создаем и заполняем тестовые данные
create table #test (Dt datetime, ind nvarchar(10), val decimal(18, 2));
insert into #test
        (Dt, ind, val)
values  ('2017-05-21 13:45:16', 'Indicator1', 15),
        ('2017-05-21 13:45:16', 'Indicator2', 13.8),
        ('2017-05-21 13:45:16', 'Indicator3', 0),
        ('2017-05-21 13:45:16', 'Indicator4', -7.1),
        ('2017-05-21 13:45:16', 'Indicator5', 0),
        ('2017-05-21 13:45:16', 'Indicator6', 24.2),
        ('2017-05-21 13:45:16', 'Indicator7', 0),
        ('2017-05-21 13:45:16', 'Indicator8', 0),
        ('2017-05-21 13:45:16', 'Indicator9', 0),
        ('2017-05-21 13:45:17', 'Indicator6', 23.2),
        ('2017-05-21 13:45:17', 'Indicator2', 14.1),
        ('2017-05-21 13:45:18', 'Indicator4', -6.4),
        ('2017-05-21 13:45:18', 'Indicator6', 21.4),
        ('2017-05-21 13:45:19', 'Indicator6', 22),
        ('2017-05-21 13:45:19', 'Indicator2', 14.2),
        ('2017-05-21 13:45:19', 'Indicator4', -5.9);


with 
--Делаем таблицу пересечения всех возможных значений, присоединяем имеющиеся значения
CreateGaps as 
(
    select  Dates.Dt, Indicators.ind, t.val
    from    (select distinct Dt from #test) as Dates
            cross join (select distinct ind from #test as t) as Indicators
            left  join #test as t
                    on t.Dt = Dates.Dt
                    and t.ind = Indicators.ind
),
--Заменяем null-овые значения на предыдущие
FillGaps as
(
    SELECT Dt, ind,
      CAST(
        SUBSTRING(
          MAX( CAST(Dt AS BINARY(4)) + 
               cast(ind as binary(20)) + 
               cast(val AS BINARY(9)) )
            OVER( partition by Ind order BY Dt
                  ROWS UNBOUNDED PRECEDING ),
          24, 9)
        AS decimal(18, 2)) AS val
    FROM CreateGaps
)
--Разворачиваем таблицу с использованием PIVOT
select Dt, [Indicator1], [Indicator2], [Indicator3]
         , [Indicator4], [Indicator5], [Indicator6]
         , [Indicator7], [Indicator8], [Indicator9]
 from FillGaps as t
 pivot (max(val) for ind in 
          ([Indicator1], [Indicator2], [Indicator3]
          ,[Indicator4], [Indicator5], [Indicator6]
          ,[Indicator7], [Indicator8], [Indicator9])
       ) as pvt;

drop table #test

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.