22,207
社区成员
发帖
与我相关
我的任务
分享
select name,ID,
monday=MAX(case when theday='theday' then number end),
tuesday=MAX(case when theday='tuesday' then number end),
wednesday=MAX(case when theday='wednesday' then number end),
thursday=MAX(case when theday='thursday' then number end),
friday=MAX(case when theday='friday' then number end),
saturday=MAX(case when theday='saturday' then number end),
sunday=MAX(case when theday='sunday' then number end)
from tb2
group by name,ID
--1.
select name,id,'monday' as theday,monday from tb1
union all
select name,id,'tuesday' as theday,tuesday from tb1
union all
select name,id,'wednesday' as theday,wednesday from tb1
union all
select name,id,'thursday' as theday,thursday from tb1
union all
select name,id,'friday' as theday,friday from tb1
union all
select name,id,'saturday' as theday,saturday from tb1
union all
select name,id,'sunday' as theday,sunday from tb1
order by 1,2
/**
name id theday monday
---------- ---------- --------- ----------
小李 00003 monday 10
小李 00003 tuesday 50
小李 00003 wednesday 40
小李 00003 thursday 20
小李 00003 friday 10
小李 00003 saturday 30
小李 00003 sunday 50
小刘 00005 sunday 100
小刘 00005 friday 20
小刘 00005 saturday 10
小刘 00005 thursday 60
小刘 00005 wednesday 20
小刘 00005 tuesday 50
小刘 00005 monday 20
小王 00002 monday 20
小王 00002 tuesday 30
小王 00002 wednesday 20
小王 00002 thursday 20
小王 00002 friday 20
小王 00002 saturday 30
小王 00002 sunday 50
小张 00001 sunday 30
小张 00001 saturday 10
小张 00001 friday 20
小张 00001 wednesday 20
小张 00001 thursday 20
小张 00001 monday 10
小张 00001 tuesday 10
小赵 00004 tuesday 30
小赵 00004 monday 40
小赵 00004 wednesday 20
小赵 00004 thursday 20
小赵 00004 friday 20
小赵 00004 saturday 30
小赵 00004 sunday 50
(所影响的行数为 35 行)
**/
--2.
select name,id,
max(case when theday='monday' then number else 0 end) as [monday],
max(case when theday='tuesday' then number else 0 end) as [tuesday],
max(case when theday='wednesday' then number else 0 end) as [wednesday],
max(case when theday='thursday' then number else 0 end) as [thursday],
max(case when theday='friday' then number else 0 end) as [friday],
max(case when theday='saturday' then number else 0 end) as [saturday],
max(case when theday='sunday' then number else 0 end) as [sunday]
from tb2
group by name,id
/**
name id monday tuesday wednesday thursday friday saturday sunday
---------- ---------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
小张 00001 10 10 20 20 20 10 10
小王 00002 20 30 20 20 20 30 50
(所影响的行数为 2 行)
**/
-- tb2->tb1
SELECT name,id,[monday], [tuesday], [wednesday], [thursday], [friday],[saturday],[sunday]
FROM tb2
PIVOT
(
max (number)
FOR theday IN
( [monday], [tuesday], [wednesday], [thursday], [friday],[saturday],[sunday] )
) AS pvt
ORDER BY id;
-- tb1->tb2
SELECT name,id, theday, number
FROM tb1
UNPIVOT
( number FOR theday IN
([monday], [tuesday], [wednesday], [thursday], [friday],[saturday],[sunday])
)AS unpvt