Tuesday, February 3, 2015

Rezolvare problema lui Danezu



create table Datetimes
(
       Date1 datetime,
       Date2 datetime,
       Date3 datetime,
       Date4 datetime,
       Date5 datetime
)

declare @i int
set @i = 1000

while (@i>0)
begin
       insert into Datetimes values(DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0),DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0),DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0),DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0),DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0))
       set @i = @i - 1
end


go

select
max(Date) from
(
select max(Date1) a1 ,max(Date2) a2, max(Date3) a3, max(Date4) a4, max(Date5) a5 from Datetimes
)
t
unpivot
(
       Date for Dates in ([a1],[a2], [a3],[a4],[a5])
) as UnPvt

Pivot / Unpivot


create table Cart
(
    Product varchar(32),
    Color varchar(32),
    Nr int
)

insert into Cart values ('car','blue',3)
insert into Cart values ('car','red',2)
insert into Cart values ('car','black',3)
insert into Cart values ('car','white',1)
insert into Cart values ('car','blue',1)
insert into Cart values ('carrot','blue',3)
insert into Cart values ('carrot','red',2)
insert into Cart values ('onion','black',3)
insert into Cart values ('onion','white',1)
insert into Cart values ('car','blue',1)
insert into Cart values ('beer','blue',3)
insert into Cart values ('car','red',2)
insert into Cart values ('car','black',3)
insert into Cart values ('beer','white',1)
insert into Cart values ('car','blue',1)
insert into Cart values ('carrot','blue',3)
insert into Cart values ('beer','red',2)
insert into Cart values ('onion','black',3)
insert into Cart values ('onion','white',1)
insert into Cart values ('car','blue',1)
insert into Cart values ('car','blue',1)
insert into Cart values ('beer','blue',3)
insert into Cart values ('car','red',2)
insert into Cart values ('beer','black',3)
insert into Cart values ('beer','white',1)
insert into Cart values ('car','blue',1)
insert into Cart values ('car','blue',3)
insert into Cart values ('beer','red',2)



select * into CartPivot  from Cart
pivot
(
    sum(Nr)
    for Color in ([blue],[black],[white],[red])
) PivotTable



select * from CartPivot


select Product, Nr, details from CartPivot
Unpivot
(
  Nr for details in  ([blue],[black],[white],[red])
) as UnPvt