私はテーブルを持っています(以下のスクリプト):
use master
go
--
--
if db_id ( 'CrossApplyDemo' ) is not null
drop database CrossApplyDemo
go
create database CrossApplyDemo
go
use CrossApplyDemo
go
--
if object_id ( 'dbo.Countries', 'U' ) is not null
drop table dbo.Countries
go
create table dbo.Countries ( CountryID int, Country nvarchar(255) )
go
--
insert into dbo.Countries ( CountryID, Country )
values ( 1, N'Russia' ), ( 2, N'USA' ), ( 3, N'Germany' )
, ( 4, N'France' ), ( 5, N'Italy' ), ( 6, N'Spain' )
go
--
if object_id ( 'dbo.Cities', 'U' ) is not null
drop table dbo.Cities
go
create table dbo.Cities ( CityID int, CountryID int, City nvarchar(255) )
go
--
insert into dbo.Cities ( CityID, CountryID, City )
values ( 1, 1, N'Moscow' ), ( 2, 1, N'St. Petersburg' ), ( 3, 1, N'Yekaterinburg' )
, ( 4, 1, N'Novosibirsk' ), ( 5, 1, N'Samara' ), ( 6, 2, N'Chicago' )
, ( 7, 2, N'Washington' ), ( 8, 2, N'Atlanta' ), ( 9, 3, N'Berlin' )
, ( 10, 3, N'Munich' ), ( 11, 3, N'Hamburg' ), ( 12, 3, N'Bremen' )
, ( 13, 4, N'Paris' ), ( 14, 4, N'Lyon' ), ( 15, 5, N'Milan' )
go
国ごとにグループ化した都市を選択します。2つのアプローチを使用してクエリを実行できます。
-- using join:
select *
from CrossApplyDemo.dbo.Countries as countries
inner join CrossApplyDemo.dbo.Cities as cities on cities.CountryID = countries.CountryID
-- using apply
select *
from CrossApplyDemo.dbo.Countries as countries
cross apply (select * from CrossApplyDemo.dbo.Cities as cities where cities.CountryID = countries.CountryID) as c;
以下の「applyquery」と同じ結果を返すことができる「crossapply」のないクエリはどこにありますか?:
select *
from CrossApplyDemo.dbo.Countries as countries
cross apply (select top(3) * from CrossApplyDemo.dbo.Cities as cities where cities.CountryID = countries.CountryID) as c;
クエリ:
select top(3) *
from CrossApplyDemo.dbo.Countries as countries
inner join CrossApplyDemo.dbo.Cities as cities on cities.CountryID = countries.CountryID
うまくいかない