2015-06-17 2 views
1

Мне нужно заполнить таблицу Rota для драйверов из документа excel, где хранятся номера идентификаторов поездки.Извлечение нескольких, но не всех полей, но одного столбца

на загрузку в приложение, мне нужно это, чтобы принести время начала этого запуска из таблицы выполняется в течение каждого дня с помощью SP

Эта часть не является проблемой, и все прекрасно работает проблема начинается тогда, когда определенные дни являются «0» (выходной день), поэтому, если драйвер не используется для ежедневной недели, данные не возвращаются.

Я знаю, что это не очень привлекательный SQL, но это просто быстрый макет, чтобы объяснить проблему.

Вот T-SQL

( 
@runid0 as int = 0, 
@runid1 as int = 0, 
@runid2 as int = 0, 
@runid3 as int = 0, 
@runid4 as int = 0, 
@runid5 as int = 0, 
@runid6 as int = 0, 
@siteid as int 

) 
AS 
declare @effectivedate0 as datetime 
declare @effectivedate1 as datetime 
declare @effectivedate2 as datetime 
declare @effectivedate3 as datetime 
declare @effectivedate4 as datetime 
declare @effectivedate5 as datetime 
declare @effectivedate6 as datetime 

set @effectivedate0 = (Select TOP 1 effective_from FROM db_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @effectivedate1 = (Select TOP 1 effective_from FROM db_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @effectivedate2 = (Select TOP 1 effective_from FROM db_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @effectivedate3 = (Select TOP 1 effective_from FROM db_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @effectivedate4 = (Select TOP 1 effective_from FROM db_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @effectivedate5 = (Select TOP 1 effective_from FROM db_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @effectivedate6 = (Select TOP 1 effective_from FROM db_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 

Select * From 
    (SELECT arrival as arr0 from db_t_run_orders where run_id = @runid0 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate0) a 
    Cross Join 
    (SELECT arrival as arr1 from db_t_run_orders where run_id = @runid1 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate1) b 
    Cross Join 
    (SELECT arrival as arr2 from db_t_run_orders where run_id = @runid2 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate2) c 
    Cross Join 
    (SELECT arrival as arr3 from db_t_run_orders where run_id = @runid3 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate3) d 
    Cross Join 
    (SELECT arrival as arr4 from db_t_run_orders where run_id = @runid4 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate4) e 
    Cross Join 
    (SELECT arrival as arr5 from db_t_run_orders where run_id = @runid5 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate5) f 
    Cross Join 
    (SELECT arrival as arr6 from db_t_run_orders where run_id = @runid6 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate6) g 

RETURN 
+0

Это просто возвращается 1 строку с 7 столбцов, одно значение для каждого из @runids и результат 0 строк, потому что один из наборов результатов пуст? Не могли бы вы изменить шаблон пересечения, чтобы объединить все, а затем повернуть результат в столбцы? –

+0

Привет, да 1 строка с 7 столбцами - это то, что им нужно, но если runid равен 0, тогда мне нужна эта колонка, чтобы быть пустой, например, дни солнца, чтобы работать на работе '--- 0 ------ 1-- ------ 2 ------ 3 -------- 4 -------- 5 ------- 6 - ' ' 10:00 12:00 10:00 10:00 - - - ' никогда не использовал функцию поворота, прежде чем я немного поработаю и вернусь к вам – user3652973

ответ

0

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

Просто объявляйте переменные для каждого дня и запускайте сингулярные запросы для каждой переменной, выгружайте их в таблицу temp и выберите * таблицу.

он будет более эффективным, чем комбинированный запрос, возможно, нет. это самый чистый/самый краткий подход, определенно нет. это делает работу да.

Если кто-то хочет опубликовать лучшую версию, очевидно, сделайте это.

( 
@runid0 as int = 0, 
@runid1 as int = 0, 
@runid2 as int = 0, 
@runid3 as int = 0, 
@runid4 as int = 0, 
@runid5 as int = 0, 
@runid6 as int = 0, 
@siteid as int 

) 

КАК объявляют @ effectivedate0 как даты и времени объявляют @ effectivedate1 как даты и времени объявляют @ effectivedate2 как даты и времени объявляют @ effectivedate3 как даты и времени объявляют @ effectivedate4 как даты и времени объявляют @ effectivedate5 как даты и времени объявляют @ effectivedate6 как DateTime объявить @ arr0, как VARCHAR (5) объявить @ arr1, как VARCHAR (5) объявить @ arr2, как VARCHAR (5) объявить @ arr3, как VARCHAR (5) объявляют @ arr4 как вар символ (5) объявить @ arr5, как VARCHAR (5) объявить @ arr6, как VARCHAR (5)

Declare @table Table (day0 varchar(5), day1 varchar(5), day2 varchar(5), day3 varchar(5), day4 varchar(5), day5 varchar(5), day6 varchar(5)) 

BEGIN 
set @effectivedate0 = (Select TOP 1 effective_from FROM dbo_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @arr0 = (SELECT arrival as arr from dbo_t_run_orders where run_id = @runid0 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate0) 
END 
BEGIN 
set @effectivedate1 = (Select TOP 1 effective_from FROM dbo_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @arr1 = (SELECT arrival as arr from dbo_t_run_orders where run_id = @runid1 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate1) 
END 
BEGIN 
set @effectivedate2 = (Select TOP 1 effective_from FROM dbo_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @arr2 = (SELECT arrival as arr from dbo_t_run_orders where run_id = @runid2 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate2) 
END 
BEGIN 
set @effectivedate3 = (Select TOP 1 effective_from FROM dbo_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @arr3 = (SELECT arrival as arr from dbo_t_run_orders where run_id = @runid3 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate3) 
END 
BEGIN 
set @effectivedate4 = (Select TOP 1 effective_from FROM dbo_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @arr4 = (SELECT arrival as arr from dbo_t_run_orders where run_id = @runid4 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate4) 
END 
BEGIN 
set @effectivedate5 = (Select TOP 1 effective_from FROM dbo_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @arr5 = (SELECT arrival as arr from dbo_t_run_orders where run_id = @runid5 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate5) 
END 
BEGIN 
set @effectivedate6 = (Select TOP 1 effective_from FROM dbo_t_run_plan WHERE effective_from <= GetDATE() AND [email protected] AND [email protected] order by effective_from DESC) 
set @arr6 = (SELECT arrival as arr from dbo_t_run_orders where run_id = @runid6 and [email protected] and trip_no=1 and visit_order = 1 and effective_from = @effectivedate6) 
END 

insert into @table values (@arr0,@arr1,@arr2,@arr3,@arr4,@arr5,@arr6) 

select * from @table 



RETURN 
+0

Да, это тоже работает, но вместо того, чтобы иметь таблицу, вы могли бы просто выбрать @ arr0 , + другие переменные .. - и, кстати, начальные + концевые блоки на самом деле ничего не делают, кроме того, что сделать его труднее читать. –

+0

Прохладный спасибо за это, по общему признанию, начало концов - это всего лишь плохая привычка, которую я взял, когда узнал, что кто-то сказал мне в основном, если у вас есть более одного запроса, инкапсулируйте его. – user3652973

Смежные вопросы