ABCDEF
1
1Количество продаж товаров по месяцам
/* Количество продаж товаров по месяцам */ select count(rs.OrderDateKey) as c, t.EnglishMonthName, p.ProductKey from FactResellerSales as rs inner join DimProduct as p on rs.ProductKey=p.ProductKey inner join DimTime as t on rs.OrderDateKey=t.TimeKey group by t.EnglishMonthName, p.ProductKey order by c desc compute max(count(rs.OrderDateKey))
2
2Старейший сотрудник
/*Старейший сотрудник*/ select e1.* from DimEmployee as e1 where e1.BirthDate = (select min(e2.BirthDate) from DimEmployee as e2) /*Старейшая сотрудница*/ select * from DimEmployee where Gender='F' AND BirthDate = (select min(BirthDate) from DimEmployee where Gender='F')
3
3Поиск однофамильцев среди сотрудников
/*Найти однофамильцев (первый способ)*/ select e1.EmployeeKey, e2.EmployeeKey, e1.LastName, e2.LastName from DimEmployee as e1, DimEmployee as e2 where e1.LastName = e2.LastName And e1.EmployeeKey < e2.EmployeeKey order by e1.EmployeeKey, e2.EmployeeKey /*Найти однофамильцев (второй способ)*/ select distinct 'k'=e1.EmployeeKey, 'l'=e1.LastName from DimEmployee as e1, DimEmployee as e2 where e1.LastName = e2.LastName And e1.EmployeeKey <> e2.EmployeeKey and e1.Status is not null and e2.Status is not null order by e1.LastName, e1.EmployeeKey
4
4Добавление, правка, удаление записей в таблицу
/*Добавление, правка, удаление */ declare @tt table(id int, ename nvarchar(50)); insert into @tt select ProductCategoryKey, EnglishProductCategoryName from DimProductCategory -- распечатка таблицы select * from @tt -- добавление записей insert into @tt(id, ename) values (6, 'New') insert into @tt(id, ename) values (7, 'More') -- распечатка таблицы select * from @tt -- правка записей update @tt set ename = 'Change' where id between 2 and 4 -- распечатка таблицы select * from @tt -- удаление записей delete from @tt where ename = 'Change' -- распечатка таблицы select * from @tt
5
5Территория продаж распространителей
/* Проверка совпадения территории продажи и территории перепродавца (магазина) */ select fr.* from FactResellerSales as fr inner join DimReseller as r on fr.ResellerKey=r.ResellerKey inner join DimGeography as g on r.GeographyKey=g.GeographyKey inner join DimSalesTerritory as t on g.SalesTerritoryKey=t.SalesTerritoryKey where fr.SalesTerritoryKey<>t.SalesTerritoryKey
6
6Территории продаж сотрудников
/* Сотрудники, совершавшие сделки на "своей" и на "не своей" территории */ --вычисляются продажи сначала на "не своей", а за тем на "своей" территории --в итоговой таблице объединяются оба запроса при помощи команды UNION --в поле 'territory' выводится текстовая строка, принимающая одно из двух значений: -- '!=' - для "не своей" территории -- '=' - для "своей" территории select distinct e.EmployeeKey , '!=' as 'territory' from FactResellerSales as fr inner join DimEmployee as e on fr.EmployeeKey=e.EmployeeKey inner join DimSalesTerritory as t on e.SalesTerritoryKey=t.SalesTerritoryKey where fr.SalesTerritoryKey<>t.SalesTerritoryKey UNION select distinct e.EmployeeKey , '=' as 'territory' from FactResellerSales as fr inner join DimEmployee as e on fr.EmployeeKey=e.EmployeeKey inner join DimSalesTerritory as t on e.SalesTerritoryKey=t.SalesTerritoryKey where fr.SalesTerritoryKey=t.SalesTerritoryKey order by e.EmployeeKey
7
7Вычисление разности курсов валют
/*Вычисление разности курсов валют*/ --код валюты declare @ck int; --временная таблица для хранения промежуточных вычислений declare @dif_table table(tk int, av_rate float, dif_rate float); set @ck=3; --вычисление разности среднего курса между текущем и следующим днём для всех дней insert into @dif_table select TimeKey, AverageRate, 'dif'= AverageRate - ( select AverageRate from FactCurrencyRate fr where fr.CurrencyKey=f.CurrencyKey and fr.TimeKey = f.TimeKey + 1 ) from FactCurrencyRate f where CurrencyKey=@ck; --вычисление наибольшей разности валют между соседними днями select * from @dif_table where dif_rate=(select max(dif_rate) from @dif_table);
8
8Курсы каких валют и за сколько дней представлены
/*Какие валюты и за сколько дней представлены в таблице курсов валют*/ select count(*), c.CurrencyName, c.CurrencyKey from FactCurrencyRate f inner join DimCurrency c on f.CurrencyKey = c.CurrencyKey group by c.CurrencyName, c.CurrencyKey
9
9Выборка работников с общим числом продаж меньше половины среднего
/* Выбираются работники с числом продаж меньше половины среднего */ --временная таблица для хранения промежуточных вычислений declare @t_cnt table(cnt int, emp int); --вычисляется общее число продаж каждого сотрудника insert into @t_cnt select count(*), f.EmployeeKey from FactResellerSales f group by f.EmployeeKey --среднее значение числа продаж среди всех сотрудников declare @a int; set @a = (select avg(cnt) from @t_cnt) --распечатка среднего значения select 'a' = @a --выбор сотрудников с числом продаж меньшим половины среднего значения select cnt, e.* from @t_cnt inner join DimEmployee e on emp = e.EmployeeKey where cnt < @a / 2
10
10Выборка работников со среднемесячным числом продаж меньше половины среднего
/* Выбираются работники со среднемесячным числом продаж меньше половины среднего */ --временная таблица для хранения числа продаж каждого сотрудника в каждом месяце declare @t_cnt table(cnt int, emp int); insert into @t_cnt select count(*), f.EmployeeKey from FactResellerSales f inner join DimTime t on f.OrderDateKey = t.TimeKey group by f.EmployeeKey, t.EnglishMonthName, t.CalendarYear --временная таблица для хранения среднемесячного числа продаж каждого сотрудника declare @t_av table(av int, emp int); insert into @t_av select avg(cnt), emp from @t_cnt group by emp --переменная, хранящее среднее значение среднемесячных чисел продаж по всем сотрудникам declare @a int; set @a = (select avg(av) from @t_av) --распечатка select 'a'=@a --выборка сотрудников со среднемесячным числом продаж, --меньшим половины среднего значения среднемесячных чисел продаж по всем сотрудникам select av, e.* from @t_av inner join DimEmployee e on emp = e.EmployeeKey where av < @a / 2
11
11Поиск максимумов курса валюты с использованием цикла
/*Локальные максимумы курса валюты (с использованием цикла)*/ declare @cr int; set @cr=102; --код валюты declare @tid int; declare @tidc int; set @tid = (select min(TimeKey) from FactCurrencyRate where CurrencyKey=@cr) + 1 --select 't' = @tid declare @tt table(tid int, rate float, flag int) while exists (select * from FactCurrencyRate where CurrencyKey=@cr and TimeKey = @tid) begin declare @a0 float, @a1 float, @a2 float; set @a0 = (select AverageRate from FactCurrencyRate where CurrencyKey=@cr and TimeKey = @tid - 1) set @a1 = (select AverageRate from FactCurrencyRate where CurrencyKey=@cr and TimeKey = @tid) set @a2 = (select AverageRate from FactCurrencyRate where CurrencyKey=@cr and TimeKey = @tid + 1) if @a0 < @a1 and @a1 > @a2 begin insert into @tt(tid, rate, flag) values(@tid - 1, @a0, 0) insert into @tt(tid, rate, flag) values(@tid , @a1, 1) insert into @tt(tid, rate, flag) values(@tid + 1, @a2, 2) end set @tid = @tid + 1; end select * from @tt
12
12Поиск максимумов курса валюты с использованием дополнительных таблиц
/*Локальные максимумы курса валюты (с использованием дополнительных таблиц)*/ declare @cr int; set @cr=102; declare @tid_min int; declare @tid_max int; set @tid_min = (select min(TimeKey) from FactCurrencyRate where CurrencyKey=@cr) set @tid_max = (select max(TimeKey) from FactCurrencyRate where CurrencyKey=@cr) declare @tt0 table(tid int, rate float) declare @tt1 table(tid int, rate float) declare @tt2 table(tid int, rate float) insert into @tt0 select TimeKey + 1, AverageRate from FactCurrencyRate where CurrencyKey=@cr and TimeKey between @tid_min and @tid_max - 2 insert into @tt1 select TimeKey, AverageRate from FactCurrencyRate where CurrencyKey=@cr and TimeKey between @tid_min + 1 and @tid_max - 1 insert into @tt2 select TimeKey - 1, AverageRate from FactCurrencyRate where CurrencyKey=@cr and TimeKey between @tid_min + 2 and @tid_max select t1.tid, t0.rate, t1.rate, t2.rate from @tt0 t0 inner join @tt1 t1 on t0.tid = t1.tid inner join @tt2 t2 on t2.tid = t1.tid where t0.rate < t1.rate and t1.rate > t2.rate
13
13Поиск максимумов курса валюты в одном запросе
/*Локальные максимумы курса валюты (в одном запросе)*/ /*Вычисление разности курсов валют*/ declare @currencyKey int; set @currencyKey = 3; select timeKey, AverageRate, (select AverageRate from FactCurrencyRate as f2 where f2.timeKey = f1.timeKey + 1 and currencyKey=f1.currencyKey) as nextAvarageRate, (select AverageRate from FactCurrencyRate as f2 where f2.timeKey = f1.timeKey - 1 and currencyKey=f1.currencyKey) as lastAvarageRate from FactCurrencyRate as f1 where currencyKey = @currencyKey and Averagerate > (select AverageRate from FactCurrencyRate as f2 where f2.timeKey = f1.timeKey + 1 and currencyKey=f1.currencyKey) and Averagerate > (select AverageRate from FactCurrencyRate as f2 where f2.timeKey = f1.timeKey - 1 and currencyKey=f1.currencyKey)
14
15
16
17
18
19
20