-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1. Databases in Sql server.sql
90 lines (65 loc) · 1.97 KB
/
1. Databases in Sql server.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
-- creating Database
create database Demo;
--To know all databases details
select * from sys.databases
exec sp_databases
--To know all databases names
select name from sys.databases order by 1
select name from sys.databases order by name
-- To rename database name
alter database demo modify name=Prac
alter database Prac modify name=demo
exec sp_renamedb 'demo','Prac'
create table entries (
name varchar(20),
address varchar(20),
email varchar(20),
floor int,
resources varchar(10));
insert into entries
values
('A','Bangalore','[email protected]',1,'CPU'),
('A','Bangalore','[email protected]',1,'CPU'),
('A','Bangalore','[email protected]',2,'DESKTOP'),
('B','Bangalore','[email protected]',2,'DESKTOP'),
('B','Bangalore','[email protected]',2,'DESKTOP'),
('B','Bangalore','[email protected]',1,'MONITOR');
select * from entries;
with test as (
select name
,floor
,count(floor) as floor_count
,ROW_NUMBER() OVER (PARTITION BY name ORDER BY COUNT(*) DESC) AS visit_rank
from entries
group by name, floor
),
test2 as (
select distinct name, resources from entries
)
,test3 as (
select name, string_agg(resources,',') as all_res from test2 group by name
)
select entries.name
,count(*) as visits
,test.floor,all_res as res from entries
join test on entries.name = test.name
join test3 on entries.name = test3.name
where visit_rank =1
group by entries.name, test.floor, all_res
with test as (
select name,floor,count(floor) as floor_count,
rank() over (partition by name order by count(floor) desc) as rank from entries group by name, floor)
,
test2 as (
select distinct name, resources from entries
)
,test3 as (
select name, string_agg(resources,',') as all_res from test2 group by name
)
select entries.name
,count(*) as visits
,test.floor,all_res as res from entries
join test on entries.name = test.name
join test3 on entries.name = test3.name
where rank =1
group by entries.name, test.floor, all_res