这是SQL Server的输出,我不知道PostgreSQL的。
- 创建SETS
create table dbo.test_sets
(
id int not null,
name varchar(255),
initial_value int not null default (0),
final_value int not null default(0)
)
go
insert into dbo.test_sets(id, name, initial_value, final_value)
values (1, 'X', 40, 50)
insert into dbo.test_sets(id, name, initial_value, final_value)
values (2, 'Y', 30, 60)
insert into dbo.test_sets(id, name, initial_value, final_value)
values (3, 'Z', 20, 70)
go
- 创建ITEMS
create table dbo.test_items
(
id int not null,
[date] date,
store varchar(255) not null,
model varchar(255) not null,
size int not null default (0),
in_stock int not null default(0)
)
go
insert into dbo.test_items(id, [date], store, model, size, in_stock)
values (1, '02/26/2016', 'A', 'shirt', 40, 1)
insert into dbo.test_items(id, [date], store, model, size, in_stock)
values (2, '02/26/2016', 'A', 'shirt', 50, 2)
insert into dbo.test_items(id, [date], store, model, size, in_stock)
values (3, '02/26/2016', 'A', 'shirt', 30, 0)
insert into dbo.test_items(id, [date], store, model, size, in_stock)
values (4, '02/26/2016', 'B', 'shirt', 30, 1)
insert into dbo.test_items(id, [date], store, model, size, in_stock)
values (5, '02/26/2016', 'C', 'shirt', 80, 1)
go
- 创建NUMBERS LOOKUP
create table dbo.test_numbers
(
id int not null
)
go
declare @first as int
declare @step as int
declare @last as int
select @first = 1, @step = 1, @last = 100
BEGIN TRANSACTION
WHILE(@first <= @last)
BEGIN
INSERT INTO dbo.test_numbers VALUES(@first) SET @first += @step
END
COMMIT TRANSACTION
go
- 提供所需查询输出
;with unique_store_models as
(
select distinct store, model from dbo.test_items
),
set_sizes as
(
select ts.id, ts.name as size_group, tn.id as size
from
dbo.test_sets ts
inner join dbo.test_numbers tn on
tn.id between ts.initial_Value and ts.final_value
),
items_by_sizes_flat as
(
select
ti.[date],
usm.store,
usm.model,
ss.size_group,
ss.size,
ti.in_stock
from
unique_store_models usm
left outer join dbo.test_items ti on
ti.store = usm.store
and ti.model = usm.model
left outer join set_sizes ss on
ss.size = ti.size
),
items_by_sizes_pivoted as
(
select
*
from
(
select
[date],
store,
model,
size_group,
--size,
in_stock
from
items_by_sizes_flat
) as p
PIVOT
(
count(in_stock) for size_group in ([X], [Y], [Z])
) as pv
)
select
[date],
store,
model,
case
when [X] > 0 then 'Yes' else 'No'
end as [Availability X],
case
when [Y] > 0 then 'Yes' else 'No'
end as [Availability Y],
case
when [Z] > 0 then 'Yes' else 'No'
end as [Availability Z]
from
items_by_sizes_pivoted
下面是上述输入的输出:
目前还不清楚有 “ALL” 的定义。 “所有大小在40和50之间” - 这是否意味着41,42,43,44,45,46,47 .... 50? – Olli
是的,先生,就是这样。 –
'crosstab()'这个经典的例子' –