I have a table [dbo].[UserImages] where user uploads their photos after every 6 day, total 18 records for user 3. 9 records of day 1 and 9 records of day 6. There are 4 columns In this table [Id, UserId, Image, Day]
Id UserId Image Day
1 3 3_20200408_1.png 1
2 3 3_20200408_2.png 1
3 3 3_20200408_3.png 1
4 3 3_20200408_4.png 1
5 3 3_20200408_5.png 1
6 3 3_20200408_6.png 1
7 3 3_20200408_7.png 1
8 3 3_20200408_8.png 1
9 3 3_20200408_9.png 1
10 3 3_20200410_9.png 6
11 3 3_20200410_2.png 6
12 3 3_20200410_3.png 6
13 3 3_20200410_4.png 6
14 3 3_20200410_5.png 6
15 3 3_20200410_6.png 6
16 3 3_20200410_7.png 6
17 3 3_20200410_8.png 6
18 3 3_20200410_9.png 6
I need something like that
ImgCount UserId ImageDay1 ImageDay6 1 3 3_20200408_1.png 3_20200408_1.png 2 3 3_20200408_2.png 3_20200408_2.png 3 3 3_20200408_3.png 3_20200408_3.png 4 3 3_20200408_4.png 3_20200408_4.png 5 3 3_20200408_5.png 3_20200408_5.png 6 3 3_20200408_6.png 3_20200408_6.png 7 3 3_20200408_7.png 3_20200408_7.png 8 3 3_20200408_8.png 3_20200408_8.png 9 3 3_20200408_9.png 3_20200408_9.png
What should I do for this
You can use row_number()
and aggregation:
select
imgCount,
userId,
max(case when day = 1 then image end) ImageDay1,
max(case when day = 6 then image end) ImageDay6
from (
select t.*, row_number() over(partition by userId, day order by image) imgCount
from mytable t
where day in (1, 6)
) t
group by userId, imgCount
order by ImgCount
ImgCount | userId | ImageDay1 | ImageDay6 :------- | -----: | :--------------- | :--------------- 1 | 3 | 3_20200408_1.png | 3_20200410_1.png 2 | 3 | 3_20200408_2.png | 3_20200410_2.png 3 | 3 | 3_20200408_3.png | 3_20200410_3.png 4 | 3 | 3_20200408_4.png | 3_20200410_4.png 5 | 3 | 3_20200408_5.png | 3_20200410_5.png 6 | 3 | 3_20200408_6.png | 3_20200410_6.png 7 | 3 | 3_20200408_7.png | 3_20200410_7.png 8 | 3 | 3_20200408_8.png | 3_20200410_8.png 9 | 3 | 3_20200408_9.png | 3_20200410_9.png
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.