blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
3
276
src_encoding
stringclasses
33 values
length_bytes
int64
23
9.61M
score
float64
2.52
5.28
int_score
int64
3
5
detected_licenses
listlengths
0
44
license_type
stringclasses
2 values
text
stringlengths
23
9.43M
download_success
bool
1 class
56a5e0763ce020739da8b71f65705ea03e55054b
SQL
deawx/redbox-scan
/examples/assets/scan.sql
UTF-8
2,120
3.015625
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.4.10 -- http://www.phpmyadmin.net -- -- Host: localhost:3306 -- Generation Time: Dec 22, 2015 at 09:33 PM -- Server version: 5.5.42 -- PHP Version: 5.6.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `scan` -- -- -------------------------------------------------------- -- -- Table structure for table `scan` -- CREATE TABLE `scan` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `path` varchar(255) NOT NULL, `scandate` datetime NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; -- -- Dumping data for table `scan` -- INSERT INTO `scan` (`id`, `name`, `path`, `scandate`) VALUES (1, 'a scan', '/Users/johnny/Dropbox/Sites/Redbox/scan/redbox-scan/examples/assets', '2015-12-22 21:29:48'); -- -------------------------------------------------------- -- -- Table structure for table `scanitems` -- CREATE TABLE `scanitems` ( `id` int(11) NOT NULL, `scanid` int(11) NOT NULL, `itemfolder` varchar(255) NOT NULL, `itemname` varchar(255) NOT NULL, `md5hash` varchar(255) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=7131 DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `scan` -- ALTER TABLE `scan` ADD PRIMARY KEY (`id`), ADD KEY `id` (`id`); -- -- Indexes for table `scanitems` -- ALTER TABLE `scanitems` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `scan` -- ALTER TABLE `scan` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `scanitems` -- ALTER TABLE `scanitems` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7131; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
8f1a918629069287841f7d805b6b897b0943a5e1
SQL
BLRussell-09/ChinookQueries
/ChinookQuery9.sql
UTF-8
264
3.625
4
[]
no_license
-- total_sales_{year}.sql: What are the respective total sales for each of those years? select Sum(i.Total) as Sold_in_2011, (Select SUM(i.Total) from Invoice as i where Year(i.InvoiceDate) = 2009) as Sold_In_2009 from Invoice as i where Year(InvoiceDate) = 2011
true
aa37609645084c9bf73f47ab00014040a3b70db3
SQL
iFeddy/unla-bd1
/Procedimientos/sp_modelos_alta.sql
UTF-8
277
2.578125
3
[]
no_license
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_modelos_alta`( in ModeloNombre VARCHAR(45), out nResultado INT ) BEGIN set nResultado = -1; INSERT INTO autos_modelos (nombre) VALUES (ModeloNombre); IF( row_count() > 0 ) THEN set nResultado = 0; END IF; END
true
b939af57e5f9d3d7ff41f0661a735a4cfadd513a
SQL
bzzbzz7/HadoopLearn
/src/main/resources/hive/hiveQL.sql
UTF-8
3,150
3.875
4
[ "Apache-2.0" ]
permissive
-- noinspection SqlNoDataSourceInspectionForFile -- 1:创建内部表: create table student( id int, name string, age int) comment 'this is student message table' row format delimited fields terminated by '\t'; -- 从本地加载数据 load data local inpath './data/hive/student.txt' into table student; -- 从HDFS加载数据 load data inpath './data/hive/student.txt' into table student; -- 2:创建外部表 create external table external_student( id int, name string, age int) comment 'this is student message table' row format delimited fields terminated by '\t' location "/user/hive/external"; -- 加载数据 -- 直接将源文件放在外部表的目下即可 -- 这种加载方式常常用于当hdfs上有一些历史数据,而我们需要在这些数据上做一些hive的操作时使用。这种方式避免了数据拷贝开销 hdfs dfs -put ./data/hive/external_student /user/hive/external -- 3:创建copy_student表,并从student表中导入数据 create table copy_student( id int, name string, age int) comment 'this is student message table' row format delimited fields terminated by '\t'; -- 导入数据 from student stu insert overwrite table copy_student select *; -- 4:创建复杂类型的表 Create table complex_student( stu_mess ARRAY<STRING>, stu_score MAP<STRING,INT>, stu_friend STRUCT<a:STRING, b :STRING,c:STRING>) comment 'this is complex_student message table' row format delimited fields terminated by '\t' COLLECTION ITEMS TERMINATED BY ',' MAP KEYS TERMINATED BY ':'; -- #修改表名字 alter table complex rename to complex_student; -- #加载数据 load data local inpath "./data/hive/complex_student" into table complex_student; -- #截断表 :从表或者表分区删除所有行,不指定分区,将截断表中的所有分区,也可以一次指定多个分区,截断多个分区。 truncate table complex_student; -- #查询示例 select stu_mess[0],stu_score["chinese"],stu_friend.a from complex_student; -- 结果:thinkgamer 50 cyan -- 5:创建分区表partition_student create table partition_student( id int, name string, age int) comment 'this is student message table' Partitioned by (grade string,class string) row format delimited fields terminated by "\t"; -- #加载数据 load data local inpath "./data/hive/partiton_student" into table partition_student partition (grade="2013", class="34010301"); load data local inpath "./data/hive/partiton_student2" into table partition_student partition (grade="2013", class="34010302"); -- 6:桶 创建临时表 create table student_tmp( id int, name string, age int) comment 'this is student message table' row format delimited fields terminated by '\t'; -- 加载数据: load data local inpath './data/hive/student.txt' into table student_tmp; -- 创建指定桶的个数的表student_bucket create table student_bucket( id int, name string, age int) clustered by(id) sorted by(age) into 2 buckets row format delimited fields terminated by '\t'; -- 设置环境变量: set hive.enforce.bucketing = true; -- 从student_tmp 装入数据 from student_tmp insert overwrite table student_bucket select *;
true
ce2ac6c7ebcd43b4616b35a49ac46935a99827e2
SQL
ygortassiano/fideliza_source_manager
/fideliza_adroid/aba.sql
UTF-8
610
3.171875
3
[]
no_license
tab 1 parametro 17 (CAMPANHA) TAB 2 CAMPANHA / DATA FATURAMENTO /ZONA TAB 3 DATA_NAVEG / CAMPANHA / ZONA / FLAG SELECT RIID_, CAMPANHA FROM CL JOIN TAB 3 B ON $A$.CUSTOMER_ID =$B$.CUSTOMER_ID JOIN tab 2 ON tab 2.zona = tab 3 .zona WHERE trunc(data_faturamento) = trunc(sysdate -2) EXISTS (SELECT 1 FROM TAB 3 A WHERE FLAG = 0 AND A.CAMPANHA = B.CAMPANHA -1 AND A.CUSTOMER_ID = B.CUSTOMER_ID) NOT EXISTS (SELECT 1 FROM TAB 3 A WHERE FLAG = 1 AND A.CAMPANHA = B.CAMPANHA -1 AND A.CUSTOMER_ID = B.CUSTOMER_ID) AND NOTHING 1 NOTHING 2 NOTHING 3
true
9f81780aaaefae38578aeafaa57be4916e92c7b2
SQL
Konradsh/database_msc2020
/sql/zapytania/17.sql
UTF-8
149
3.234375
3
[]
no_license
SELECT round(((SELECT count(id) FROM customer WHERE customer.pesel IS NOT null AND customer.nip IS null)/count(id))*100,1) as procent from customer;
true
6dc6e598716a7ab0375b11117b2b69c3eba91b1a
SQL
todayido/integration
/db/2016-11-02-combination.sql
UTF-8
3,905
3.5
4
[]
no_license
/* SQLyog v10.2 MySQL - 5.1.73-community : Database - combination ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`combination` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `combination`; /*Table structure for table `t_permission` */ DROP TABLE IF EXISTS `t_permission`; CREATE TABLE `t_permission` ( `id` varchar(36) DEFAULT NULL, `permission_name` varchar(30) DEFAULT NULL, `permission_desc` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_permission` */ insert into `t_permission`(`id`,`permission_name`,`permission_desc`) values ('1','user:add','用户添加'),('2','user:delete','用户删除'),('3','user:update','用户修改'),('4','user:get','用户查询'); /*Table structure for table `t_query_table` */ DROP TABLE IF EXISTS `t_query_table`; CREATE TABLE `t_query_table` ( `id` varchar(36) NOT NULL COMMENT 'ID', `t_table_name` varchar(50) DEFAULT NULL COMMENT '表明', `t_role_name` varchar(50) DEFAULT NULL COMMENT '角色名', `conditions` varchar(500) DEFAULT NULL COMMENT '查询条件', `priority` int(11) DEFAULT NULL COMMENT '优先级', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_query_table` */ insert into `t_query_table`(`id`,`t_table_name`,`t_role_name`,`conditions`,`priority`) values ('1','t_user','login','username=#{username}',0),('2','t_user','admin','1=1',2); /*Table structure for table `t_role` */ DROP TABLE IF EXISTS `t_role`; CREATE TABLE `t_role` ( `id` varchar(36) NOT NULL, `role_name` varchar(36) DEFAULT NULL, `role_desc` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_role` */ insert into `t_role`(`id`,`role_name`,`role_desc`) values ('1','admin','管理员'),('2','login','普通用户'); /*Table structure for table `t_role_permission` */ DROP TABLE IF EXISTS `t_role_permission`; CREATE TABLE `t_role_permission` ( `id` varchar(36) DEFAULT NULL, `role_id` varbinary(36) DEFAULT NULL, `permission_id` varchar(36) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_role_permission` */ insert into `t_role_permission`(`id`,`role_id`,`permission_id`) values ('1','1','1'),('2','1','2'),('3','1','3'),('4','1','4'),('5','2','3'),('6','2','4'); /*Table structure for table `t_user` */ DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` varchar(32) NOT NULL, `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_user` */ insert into `t_user`(`id`,`username`,`password`) values ('1','admin','21232f297a57a5a743894a0e4a801fc3'),('2','test','098f6bcd4621d373cade4e832627b4f6'),('3','3','3'),('4','4','4'),('5','5','5'),('6','6','6'); /*Table structure for table `t_user_role` */ DROP TABLE IF EXISTS `t_user_role`; CREATE TABLE `t_user_role` ( `id` varchar(36) NOT NULL, `role_id` varchar(36) DEFAULT NULL, `user_id` varchar(36) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_user_role` */ insert into `t_user_role`(`id`,`role_id`,`user_id`) values ('1','1','1'),('2','2','1'),('3','2','2'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
true
6bd036fe760cfd599afac05c26f6e77bb8902284
SQL
housepower/ClickHouse
/tests/queries/0_stateless/01130_in_memory_parts_check.sql
UTF-8
519
3.015625
3
[ "Apache-2.0" ]
permissive
-- Tags: no-s3-storage -- Part of 00961_check_table test, but with in-memory parts SET check_query_single_value_result = 0; DROP TABLE IF EXISTS mt_table; CREATE TABLE mt_table (d Date, key UInt64, data String) ENGINE = MergeTree() PARTITION BY toYYYYMM(d) ORDER BY key SETTINGS min_rows_for_compact_part = 1000, min_rows_for_compact_part = 1000; CHECK TABLE mt_table; INSERT INTO mt_table VALUES (toDate('2019-01-02'), 1, 'Hello'), (toDate('2019-01-02'), 2, 'World'); CHECK TABLE mt_table; DROP TABLE mt_table;
true
433b91a770b84999585fad838bbbf2271a1ee040
SQL
sravanthigujjari/bat-scripts
/Sql Script.sql
UTF-8
1,326
3.671875
4
[]
no_license
select Patient_FirstName, Patient_LastName, Patient_PhoneNumber, Activation_Date, trantype from( select SubmittedFirstName as Patient_FirstName, Submittedlastname as Patient_LastName, SubmittedPatientPhone as Patient_PhoneNumber, Processdate as Activation_Date, trantype, sum(net_activation_qty) as net_activation_qty from sc_LakerClaim lc (nolock) where lc.BIN= '610739' and PCN='JT1' and GROUPNUMBER = '915691' group by SubmittedFirstName, Submittedlastname, SubmittedPatientPhone, Processdate, trantype ) lc1 where net_activation_qty = 1 and Activation_Date >= dateadd(week,-1,convert(date,getdate())) order by Activation_Date desc EXCEPT select Patient_FirstName, Patient_LastName, Patient_PhoneNumber, Activation_Date, trantype from( select SubmittedFirstName as Patient_FirstName, Submittedlastname as Patient_LastName, SubmittedPatientPhone as Patient_PhoneNumber, Processdate as Activation_Date, trantype, sum(net_activation_qty) as net_activation_qty from sc_LakerClaim lc (nolock) where lc.BIN= '610739' and PCN='JT1' and GROUPNUMBER = '915691' group by SubmittedFirstName, Submittedlastname, SubmittedPatientPhone, Processdate, trantype ) lc1 where net_activation_qty = 1 and Activation_Date < dateadd(week,-1,convert(date,getdate())) order by Activation_Date desc
true
8bf2ea1cdd0e342cc03e427dc0e11dacfb3ce2db
SQL
pixtelation/BookHive
/Customercart.sql
UTF-8
415
2.515625
3
[]
no_license
create table Customercart ( bookid int , bookcode varchar(100), bookname varchar(100), bookauthor varchar(100), bookprice int, ) select * from Customercart alter table Customercart alter column bookprice int; select sum(bookprice)from Customercart truncate table Customercart insert into Customercart (bookid,bookcode,bookname,bookauthor,bookprice) values('1','hgd','hts','vc','250')
true
c603d63e89e78177d8eabf9b45cf06ba3b6f461d
SQL
juan-skill/holbertonschool-higher_level_programming
/0x0E-SQL_more_queries/13-count_shows_by_genre.sql
UTF-8
287
3.703125
4
[]
no_license
-- lists all genres from hbtn_0d_tvshows and displays the number of shows linked to each SELECT tv_genres.name AS genre, COUNT(*) AS number_shows FROM tv_genres JOIN tv_show_genres WHERE tv_show_genres.genre_id = tv_genres.id GROUP BY tv_show_genres.genre_id ORDER BY number_shows DESC;
true
5ea425bebfc3af542de37e39cd9e2c1c005ab0a3
SQL
jitendrathakur/xxyyzz
/app/Config/Schema/jitendra.sql
UTF-8
3,953
3.125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 3.4.10.1deb1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jul 09, 2013 at 12:07 AM -- Server version: 5.5.24 -- PHP Version: 5.3.10-1ubuntu3.6 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `jitendra` -- -- -------------------------------------------------------- -- -- Table structure for table `comments` -- CREATE TABLE IF NOT EXISTS `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `post_id` int(11) NOT NULL, `comment` text NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `educations` -- CREATE TABLE IF NOT EXISTS `educations` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `course` varchar(255) NOT NULL, `start_time` datetime NOT NULL, `end_time` datetime NOT NULL, `info` text NOT NULL, `specialization` varchar(255) NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `posts` -- CREATE TABLE IF NOT EXISTS `posts` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(50) DEFAULT NULL, `body` text, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `posts` -- INSERT INTO `posts` (`id`, `title`, `body`, `created`, `modified`) VALUES (1, 'The title', 'This is the post body.', '2013-04-15 23:04:58', NULL), (2, 'A title once again', 'And the post body follows.', '2013-04-15 23:04:58', NULL), (3, 'Title strikes back', 'This is really exciting! Not.', '2013-04-15 23:04:58', NULL), (4, 'test', 'test\r\n', '2013-04-15 23:22:42', '2013-04-15 23:22:48'); -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE IF NOT EXISTS `products` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `type` varchar(255) NOT NULL, `link` varchar(255) NOT NULL, `image` varchar(255) NOT NULL, `info` text NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `role` varchar(20) DEFAULT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `works` -- CREATE TABLE IF NOT EXISTS `works` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `company_name` varchar(255) NOT NULL, `designation` varchar(255) NOT NULL, `info` text NOT NULL, `start` datetime NOT NULL, `end` datetime NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
b09ae9ccfc417c0a7a47c6852dd23c692dcc7619
SQL
Ricardo071019/pap_24_06_21
/pap (3).sql
UTF-8
15,099
3.078125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Tempo de geração: 24-Jun-2021 às 14:14 -- Versão do servidor: 10.4.17-MariaDB -- versão do PHP: 8.0.2 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Banco de dados: `pap` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `categorias` -- CREATE TABLE `categorias` ( `id_categoria` int(11) NOT NULL, `categoria` varchar(50) NOT NULL, `pagina` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Extraindo dados da tabela `categorias` -- INSERT INTO `categorias` (`id_categoria`, `categoria`, `pagina`) VALUES (1, 'Carrocaria', 'carrocaria.php'), (2, 'Pneus', 'pneus.php'), (3, 'Diagnositcos', 'diagnosticos.php'), (4, 'Revisao', 'revisao.php'), (5, 'Sitemas Travagem', 'sistemadetravagem.php'), (6, 'Sistema Eletrico e Alimentacao', 'sia.php'), (7, 'Embraiagem', 'embraiagem.php'), (8, 'Motor', 'motor.php'), (9, 'Suspensao', 'suspensao.php'), (10, 'AC e Climatizacao', 'ac.php'), (11, 'Escape', 'escape.php'), (12, 'Transmissao', 'transmissao.php'); -- -------------------------------------------------------- -- -- Estrutura da tabela `clientes` -- CREATE TABLE `clientes` ( `id_cliente` int(11) NOT NULL, `nome` varchar(50) NOT NULL, `morada` varchar(50) NOT NULL, `telefone` varchar(10) NOT NULL, `email` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Estrutura da tabela `estabelecimento` -- CREATE TABLE `estabelecimento` ( `id_estab` int(11) NOT NULL, `nome` varchar(50) NOT NULL, `imagem` varchar(50) NOT NULL, `descricao` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Estrutura da tabela `marcacoes` -- CREATE TABLE `marcacoes` ( `id_marcacao` int(11) NOT NULL, `Data` date NOT NULL, `id_servico` int(11) NOT NULL, `id_veiculo` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Estrutura da tabela `modelos` -- CREATE TABLE `modelos` ( `id_modelo` int(11) NOT NULL, `marca` varchar(50) NOT NULL, `modelo` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Estrutura da tabela `servicos` -- CREATE TABLE `servicos` ( `id_servico` int(11) NOT NULL, `id_categoria` int(11) NOT NULL, `nome` varchar(50) NOT NULL, `descricao` varchar(255) NOT NULL, `detalhe` varchar(100) NOT NULL, `imagem` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Extraindo dados da tabela `servicos` -- INSERT INTO `servicos` (`id_servico`, `id_categoria`, `nome`, `descricao`, `detalhe`, `imagem`) VALUES (1, 1, 'Oticas', 'Substituição da ótica danificada do seu automóvel (ótica não incluída)', 'GBQWGZDNSDBH', '2021.06.24-12.58.12.png'), (2, 1, 'Servico Bate Chapa', 'Reposição da geometria original ou usada do(s) painel(eis) danificado(s).', '', '2021.05.20-12.09.36.png'), (3, 1, 'Servico de Pintura', 'Reposição do visual original do(s) painel(eis) danificado(s)', '', '2021.05.20-12.10.38.png'), (4, 1, 'Tratamento Ceramico', 'Dá uma nova vida à pintura do seu carro e aumenta a durabilidade da mesma.', '', '2021.05.20-12.11.17.png'), (5, 1, 'Reparacao/Troca de Vidros', 'Avaliação do estado do vidro danificado, seguida de reparação ou troca em caso de danos profundos.', '', '2021.05.20-12.12.26.png'), (6, 1, 'Escovas Limpa Vidros', 'Substituição das escovas limpa-vidros por um kit de escovas novo, de acordo com as especificações indicadas.', '', '2021.05.20-12.15.30.png'), (7, 2, 'Substituicao de pneus', 'Troca aconselhada antes que o piso dos seus pneus seja utilizado além do seu limite de segurança. A nossa equipa indicar-lhe-á qual a melhor altura para a substituição dos seus pneus e qual o modelo indicado para o tipo de utilização que dá ao seu carro', '', '2021.05.20-12.16.41.png'), (8, 2, 'Alinhar direcao', 'Este serviço permite aumentar o tempo de vida útil dos pneus e reduzir o consumo de combustível. O ', '', '2021.05.20-12.17.12.png'), (9, 2, 'Enchimento dos pneus com Nitrogenio', 'É altamente recomendável para os pneus sobresselentes, dado que mantém a pressão dos pneus correta durante mais tempo e, provavelmente, no momento que seja forçado a utilizá-los.', '', '2021.05.20-12.18.06.png'), (10, 3, 'Diagnóstico de Problema', 'A sua viatura será inspecionada, na oficina e/ou em estrada, para detetar a origem dos problemas. O preço é válido para trabalhos realizados até o máximo de uma hora.', '', '2021.05.20-12.20.16.png'), (11, 3, 'Diagnostico Eletronico', 'Serão inspecionados os sistemas eletrónicos de segurança e de funcionamento do motor para descobrir se existem códigos de erro que indiquem problemas no veículo.', '', '2021.05.20-12.20.54.png'), (12, 3, 'Enchimento dos pneus com Nitrogenio', 'É altamente recomendável para os pneus sobresselentes, dado que mantém a pressão dos pneus correta durante mais tempo e, provavelmente, no momento que seja forçado a utilizá-los.', '', '2021.05.20-12.21.22.png'), (13, 4, 'Revisao Simples', 'Uma opção rápida e mais económica para garantir uma manutenção mínima entre revisões programadas. Inclui: Mudança de óleo recomendado pelo fabricante Filtro de óleo do motor Revisão dos principais pontos de segurança do veículo e nível dos fluídos', '', '2021.05.20-12.22.03.png'), (14, 4, 'Revisao Oficial', 'A revisão que cumpre o plano de manutenção estipulado pelo fabricante automóvel. Selecione esta opção e indique a quilometragem do seu veículo para garantir que será executada a manutenção adequada.', '', '2021.05.20-12.22.24.png'), (15, 4, 'Mudança de oleo', 'Mudança e reposição do nível do óleo de acordo com as especificações do fabricante. Filtro de óleo não incluído.', '', '2021.05.20-12.23.35.png'), (16, 5, 'Líquido de Travoes', 'O líquido de travões antigo é substituído pelo novo e o sistema de travões é sangrado, respeitando as especificações do fabricante', '', '2021.05.20-13.11.45.png'), (17, 5, 'Tambores de travao traseiros', 'Reposição dos Tambores de Travão traseiros. Peça com qualidade equivalente ao original para um sistema de travagem com fiabilidade acrescida.', '', '2021.05.20-12.25.40.png'), (18, 5, 'Pastilhas de Travao Dianteiras', 'Serão substituídas as pastilhas de travão dianteiras do seu veículo.', '', '2021.05.20-13.12.09.png'), (19, 6, 'Motor de Arranque', 'A função do motor de arranque é colocar o motor em movimento quando o condutor liga a ignição. Neste serviço esta componente é substituída por uma nova', '', '2021.05.20-12.27.48.png'), (20, 6, 'Alternador', 'O alternador é a componente que carrega a bateria do seu veículo.', '', '2021.05.20-12.28.31.png'), (21, 6, 'Servico de Pintura', 'Reposição do visual original do(s) painel(eis) danificado(s)', '', '2021.05.20-12.29.03.png'), (22, 7, 'Kit de Embraiagem', 'O preço indicado para este serviço tem em conta a substituição do kit de embraiagem de origem da sua viatura por um semelhante', '', '2021.05.20-12.29.38.png'), (23, 7, 'Volante do Motor', 'O preço indicado para este serviço tem em conta a substituição do volante do motor de origem da sua viatura por um semelhante.', '', '2021.05.20-13.10.43.png'), (24, 7, 'Bimassa', 'Isolar a transmissão das vibrações do motor', '', '2021.05.20-12.31.03.png'), (25, 8, 'Correia de Distribuicao', 'Neste serviço é mudado o kit de distribuição por completo, incluindo tensor e polia', '', '2021.05.20-12.31.40.png'), (26, 8, 'Bomba de Agua', 'Substituição da bomba de água, que é uma componente essencial para controlar a temperatura do motor e evitar avarias muito graves.', '', '2021.05.20-12.32.08.png'), (27, 8, 'Anticongelante', 'Reposição do nível de líquido anticongelante. Garante uma proteção acrescida contra a corrosão de todos os componentes do sistema de refrigeração.', '', '2021.05.20-12.32.28.png'), (28, 8, 'Tratamento Ceramico', 'A sua troca atempada ajuda a prevenir problemas no motor. Substituição do componente antigo por um novo e correta afinação de acordo com as especificações do fabricante.', '', '2021.05.20-12.33.31.png'), (29, 8, 'Suportes do motor', 'Absorve as vibrações do volante do motor e o seu peso. A sua substituição atempada garante um posicionamento do motor equilibrado.', '', '2021.05.20-13.05.13.png'), (30, 8, 'Junta da Cabeca do Motor', 'Quando a junta da cabeça do motor perde as suas propriedades, a estanquicidade das câmaras de combustão fica comprometida. Motor sem compressão (ou força), é um idicador da necessidade de intervenção.', '', '2021.05.20-13.02.57.png'), (31, 9, 'Amortecedores Dianteiros', 'O par dianteiro de amortecedores desgastados ou danificados será substituído.', '', '2021.05.20-13.03.22.png'), (32, 9, 'Amortecedores Traseiros', 'O par traseiro de amortecedores desgastados ou danificados será substituído', '', '2021.05.20-13.03.53.png'), (33, 9, 'Molas Dianteiras/Traseiras', 'O par de molas dianteiras e traseiras será substituído.', '', '2021.05.20-13.04.21.png'), (34, 10, 'Recarga do Ar Condicionado', 'A verificação do seu sistema de AC deve ser feita anualmente. Serviço de recarga do gás de ar condicionado e verificação de fugas no circuito.', '', '2021.05.20-13.06.01.png'), (35, 10, 'Desinfecao do habitaculo', 'Higienização com tratamento antibacteriano para um maior conforto e segurança dos ocupantes do veículo.', '', '2021.05.20-13.06.30.png'), (36, 10, 'Diagnostico do Sistema de Climatizacao', 'Verificação de fugas e/ou outras anomalias no sistema de Climatização. Relatório de anomalias e indicação da intervenção adequada, caso seja necessário.', '', '2021.05.20-13.07.54.png'), (37, 11, 'Sistema de Escape', 'Deteção e reparação de fugas no sistema de escape do seu automóvel. Relatório de anomalias e indicação da intervenção adequada, caso seja necessário.', '', '2021.05.20-13.08.25.png'), (38, 11, 'Diagnostico a emissao de gases', 'Verificação do nível de emissão de gases do seu carro. Relatório de anomalias e indicação da intervenção adequada, caso seja necessário.', '', '2021.05.20-13.09.00.png'), (39, 11, 'Filtro de Partículas', 'Substituição do filtro de partículas, de acordo com as especificações do fabricante. Garante o bom funcionamento do veículo e o controlo da emissão de gases poluentes.', '', '2021.05.20-13.09.31.png'), (50, 1, 'teste', 'teste 2', '', '2021.05.13-13.15.38.png'), (51, 1, 'teste2', 'mariana', '', '2021.05.20-01.01.37'); -- -------------------------------------------------------- -- -- Estrutura da tabela `utilizadores` -- CREATE TABLE `utilizadores` ( `id_utilizador` int(11) NOT NULL, `utilizador` varchar(50) NOT NULL, `nome` varchar(50) NOT NULL, `passe` int(11) NOT NULL, `tipo_uti` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Extraindo dados da tabela `utilizadores` -- INSERT INTO `utilizadores` (`id_utilizador`, `utilizador`, `nome`, `passe`, `tipo_uti`) VALUES (1, 'Ricardo', 'Ricardo', 1234, 'admin'), (2, 'mari', 'Mari', 1234, 'normal'); -- -------------------------------------------------------- -- -- Estrutura da tabela `veiculos` -- CREATE TABLE `veiculos` ( `id_veiculo` int(11) NOT NULL, `matriula` varchar(50) NOT NULL, `ano` int(11) NOT NULL, `cm` int(11) NOT NULL, `id_modelo` int(11) NOT NULL, `id_cliente` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Índices para tabelas despejadas -- -- -- Índices para tabela `categorias` -- ALTER TABLE `categorias` ADD PRIMARY KEY (`id_categoria`); -- -- Índices para tabela `clientes` -- ALTER TABLE `clientes` ADD PRIMARY KEY (`id_cliente`); -- -- Índices para tabela `estabelecimento` -- ALTER TABLE `estabelecimento` ADD PRIMARY KEY (`id_estab`); -- -- Índices para tabela `marcacoes` -- ALTER TABLE `marcacoes` ADD PRIMARY KEY (`id_marcacao`), ADD KEY `id_servico` (`id_servico`), ADD KEY `id_veiculo` (`id_veiculo`); -- -- Índices para tabela `modelos` -- ALTER TABLE `modelos` ADD PRIMARY KEY (`id_modelo`); -- -- Índices para tabela `servicos` -- ALTER TABLE `servicos` ADD PRIMARY KEY (`id_servico`), ADD KEY `id_categoria` (`id_categoria`); -- -- Índices para tabela `utilizadores` -- ALTER TABLE `utilizadores` ADD PRIMARY KEY (`id_utilizador`); -- -- Índices para tabela `veiculos` -- ALTER TABLE `veiculos` ADD PRIMARY KEY (`id_veiculo`), ADD KEY `id_modelo` (`id_modelo`), ADD KEY `id_cliente` (`id_cliente`); -- -- AUTO_INCREMENT de tabelas despejadas -- -- -- AUTO_INCREMENT de tabela `categorias` -- ALTER TABLE `categorias` MODIFY `id_categoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT de tabela `clientes` -- ALTER TABLE `clientes` MODIFY `id_cliente` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de tabela `estabelecimento` -- ALTER TABLE `estabelecimento` MODIFY `id_estab` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de tabela `marcacoes` -- ALTER TABLE `marcacoes` MODIFY `id_marcacao` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de tabela `modelos` -- ALTER TABLE `modelos` MODIFY `id_modelo` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de tabela `servicos` -- ALTER TABLE `servicos` MODIFY `id_servico` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=53; -- -- AUTO_INCREMENT de tabela `utilizadores` -- ALTER TABLE `utilizadores` MODIFY `id_utilizador` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de tabela `veiculos` -- ALTER TABLE `veiculos` MODIFY `id_veiculo` int(11) NOT NULL AUTO_INCREMENT; -- -- Restrições para despejos de tabelas -- -- -- Limitadores para a tabela `marcacoes` -- ALTER TABLE `marcacoes` ADD CONSTRAINT `marcacoes_ibfk_1` FOREIGN KEY (`id_servico`) REFERENCES `servicos` (`id_servico`), ADD CONSTRAINT `marcacoes_ibfk_2` FOREIGN KEY (`id_veiculo`) REFERENCES `veiculos` (`id_veiculo`); -- -- Limitadores para a tabela `servicos` -- ALTER TABLE `servicos` ADD CONSTRAINT `servicos_ibfk_1` FOREIGN KEY (`id_categoria`) REFERENCES `categorias` (`id_categoria`); -- -- Limitadores para a tabela `veiculos` -- ALTER TABLE `veiculos` ADD CONSTRAINT `veiculos_ibfk_1` FOREIGN KEY (`id_cliente`) REFERENCES `clientes` (`id_cliente`), ADD CONSTRAINT `veiculos_ibfk_2` FOREIGN KEY (`id_modelo`) REFERENCES `modelos` (`id_modelo`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
cfdfc9b882445acba8aaf3f433da8aab5deed140
SQL
NikeSmitt/mysql_geekbrains_course
/dz7.sql
UTF-8
1,315
4.03125
4
[]
no_license
/* Составьте список пользователей users, которые осуществили хотя бы один заказ orders в интернет магазине */ SELECT id, name FROM users WHERE id IN (SELECT user_id FROM orders); /* Выведите список товаров products и разделов catalogs, который соответствует товару. */ /* Не совсем понял, что имелось в виду, поэтому привожу два варианта*/ /* 1 */ SELECT id, name, (SELECT name FROM catalogs WHERE id = catalog_id) FROM products; /* 2 */ SELECT id, name, catalog_id FROM products WHERE catalog_id = (SELECT catalog_id FROM products WHERE name = 'AMD FX-8320'); /* (по желанию) Пусть имеется таблица рейсов flights (id, from, to) и таблица городов cities (label, name). Поля from, to и label содержат английские названия городов, поле name — русское. Выведите список рейсов flights с русскими названиями городов. */ SELECT id, (SELECT name FROM cities WHERE label = `from`) AS 'from', (SELECT name FROM cities WHERE label = `to`) AS 'to' FROM flights as `from`;
true
2d147198bb00e61f7bb6453d0ca6f7fef8f5a761
SQL
claudialphonse78/trial
/server/validator-master/sql/tablesfreeuser.sql
UTF-8
2,781
3.5625
4
[]
no_license
CREATE TABLE IF NOT EXISTS `freeuser` ( `fid` int(100) NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `fusername` varchar(200) NOT NULL, `email` varchar(200) NOT NULL, `password` varchar(200) NOT NULL, `date` varchar(100) NOT NULL, PRIMARY KEY (`fid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `products_bought` ( `id` int(100) NOT NULL AUTO_INCREMENT, `fullname` varchar(200) NOT NULL, `email` varchar(200) NOT NULL, `address` text NOT NULL, `phone` varchar(200) NOT NULL, `item_names` varchar(200) NOT NULL, `prices` varchar(100) NOT NULL, `quantity` varchar(100) NOT NULL, `amount` varchar(100) NOT NULL, `date` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `freeuser1` ( `fid` int(100) NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `fusername` varchar(200) NOT NULL, `email` varchar(200) NOT NULL, `password` varchar(200) NOT NULL, `date` varchar(100) NOT NULL, `edate` varchar(100) NOT NULL, PRIMARY KEY (`fid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; CREATE TABLE freeuser1 ( customer_id INT AUTO_INCREMENT PRIMARY KEY, customer_name VARCHAR(100) ); CREATE TABLE loginfree ( logid INT AUTO_INCREMENT PRIMARY KEY,fid INT(100), username varchar(30), password varchar(30), FOREIGN KEY (fid) REFERENCES freeuser1(fid)); CREATE TABLE orders ( order_id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT, amount DOUBLE, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ); CREATE TABLE IF NOT EXISTS `freeuser2` ( `fid` int(100) AUTO_INCREMENT, `name` varchar(200) NOT NULL, `fusername` varchar(200) NOT NULL, `email` varchar(200) NOT NULL, `password` varchar(200) NOT NULL, `rdate` varchar(100) NOT NULL, `edate` varchar(100) NOT NULL, PRIMARY KEY (`fid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `loginfree` ( `logid` int(100) AUTO_INCREMENT, `username` varchar(200) NOT NULL, `password` varchar(200) NOT NULL, PRIMARY KEY (`logid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `applicant` ( `appid` int(100) NOT NULL AUTO_INCREMENT, `fid` int(100) NOT NULL, `pid` int(100) NOT NULL, `count` int(100) NOT NULL, PRIMARY KEY (`appid`), FOREIGN KEY (`fid`) REFERENCES `freeuser2`(`fid`), FOREIGN KEY (`pid`) REFERENCES `premiumuser2`(`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `registereduser2` ( `fid` int(100), `amount` varchar(200) NOT NULL, `edate` varchar(100) NOT NULL, FOREIGN KEY (`fid`) REFERENCES `freeuser2`(`fid`) ON UPDATE CASCADE ) ENGINE=InnoDB ;
true
319e7830cc9cc43d3b9272afaa818e1b684b9fe2
SQL
TechOffice/TechOffice-Database
/010-Oracle/010-SQL/DbObject/NOT_NULL_CONSTRAINTS.sql
UTF-8
402
3.09375
3
[]
no_license
WITH function long2varchar(i_constraint_name varchar2) return varchar2 as l_search_condition LONG; begin select search_condition into l_search_condition from user_constraints where constraint_name = i_constraint_name; return substr(l_search_condition, 1, 3000); END; select * from user_constraints where long2varchar(constraint_name) like '%IS NOT NULL'; /
true
5130f095497c5d16395802c615c41b14b79b37b4
SQL
CUBRID/cubrid-testcases
/sql/_23_apricot_qa/_01_sql_extension3/_03_pseudocolumn_in_default_clause/_04_alter/_01_alter_add/cases/alter_add_012.sql
UTF-8
1,643
4.03125
4
[ "BSD-3-Clause" ]
permissive
--add columns with default value of SYSDATETIME set system parameters 'add_column_update_hard_default=yes'; create table a12(id short primary key auto_increment); insert into a12 values(null), (null), (null); select if (count(*) = 3, 'ok', 'nok') from a12; --add column with default value alter table a12 add column col1 datetime default SYSDATETIME; show columns in a12; select if(col1 is not null, 'ok', 'nok') from a12; insert into a12(id) values (null); select if ((SYSDATETIME - col1) <=1000, 'ok', 'nok') from a12 where id > 3; --add column with default value and not null constraint alter table a12 add column col2 datetime default SYSDATETIME not null; desc a12; insert into a12(col2) values (default); select if ((SYSDATETIME - col2) <=1000 and col1 = col2, 'ok', 'nok') from a12 where id > 4; --unique constraint + default alter table a12 add column col3 datetime default SYSDATETIME ; show columns in a12; alter table a12 add column col4 datetime not null; select if(col4 = datetime'01/01/0001 00:00', 'ok', 'nok') from a12; insert into a12(col4) values('2012-12-12 12:12:12.456'); select if ((SYSDATETIME - col2) <=1000 and col1 = col2, 'ok', 'nok') from a12 where id > 5; alter table a12 add column col5 datetime default '2000-12-12 12:12:12.456' not null; select if(col5 = datetime'2000-12-12 12:12:12.456', 'ok', 'nok') from a12; insert into a12(id, col3, col4) values(null, null, default(col2)); select if ((SYSDATETIME - col2) <=1000 and col1 = col2 and col5 = datetime'2000-12-12 12:12:12.456', 'ok', 'nok') from a12 where id > 6; drop table a12; set system parameters 'add_column_update_hard_default=no';
true
1fd50e901121ab9f7d7dde7219b0ee2af462693c
SQL
jamil-said/code-samples
/SQL/SQL_challenges/secondHighestSalary.sql
UTF-8
1,181
3.953125
4
[]
no_license
-- Tested on MySQL /* secondHighestSalary Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null. +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ */ SELECT (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1) AS SecondHighestSalary; /* input: {"headers": {"Employee": ["Id", "Salary"]}, "rows": {"Employee" : [[1, 100]]}} output: {"headers":["SecondHighestSalary"],"values":[[null]]} input: {"headers": {"Employee": ["Id", "Salary"]}, "rows": {"Employee" : [[1, 100], [2, 200], [3, 300]]}} output: {"headers":["SecondHighestSalary"],"values":[[200]]} input: {"headers": {"Employee": ["Id", "Salary"]}, "rows": {"Employee" : [[1, 100], [2, 100]]}} output: {"headers":["SecondHighestSalary"],"values":[[null]]} */
true
0fd4fd61af5ad0ff561a758f0fbcc9b1bc1d9a64
SQL
DmitrijR13/billAuk
/Main/DATA/IFMX/SQL/config_saha_bi.sql
WINDOWS-1251
1,737
2.65625
3
[]
no_license
database websahbi; set encryption password "IfmxPwd2"; CREATE PROCEDURE tshu_drp() on exception return; end exception with resume drop table config; END PROCEDURE; EXECUTE PROCEDURE tshu_drp(); DROP PROCEDURE tshu_drp; CREATE PROCEDURE tshu_drp() on exception return; end exception with resume create table "webdb".config ( nzp_config serial not null, nzp_role int, sign char(100) ); CREATE INDEX "webdb".ix_config_1 ON "webdb".config(nzp_role); END PROCEDURE; EXECUTE PROCEDURE tshu_drp(); DROP PROCEDURE tshu_drp; delete from config; insert into config(nzp_role) values (10); -- insert into config(nzp_role) values (947); -- - insert into config(nzp_role) values (11); -- insert into config(nzp_role) values (931); -- --- insert into config(nzp_role) values (905); -- - insert into config(nzp_role) values (12); -- insert into config(nzp_role) values (932); -- -- insert into config(nzp_role) values (14); -- insert into config(nzp_role) values (925); -- -- insert into config(nzp_role) values (18); -- update config set sign = encrypt_aes(nzp_role||'-'||nzp_config||'config'); -- Excel : 1 - , 0 - delete from sysprtdata where num_prtd in (33,330); insert into sysprtdata values (0,33,encrypt_aes(1));
true
c946cbc99cba3d416f5c566da0f2eb498682d16d
SQL
allwaysoft/Oracle-1
/Database performance tuning/Scripts/Capitulo3/06_Verificar_tempo_wait_versus_cpu.sql
UTF-8
808
3.40625
3
[]
no_license
-- VER TEMPO TOTAL DE WAITs E DE CPU ULTIMOS EVENTOS. Aqui da para ver se BD gastou mais tempo com wait events ou cpu e da p/ ver detalhes de onde foi gasto o tempo SELECT METRIC_NAME, VALUE, metric_unit FROM V$SYSMETRIC WHERE METRIC_NAME IN ('Database CPU Time Ratio','Database Wait Time Ratio') AND INTSIZE_CSEC = (select max(INTSIZE_CSEC) from V$SYSMETRIC); -- ver media da ultima hora de varias metricas do BD SELECT metric_name, average, metric_unit FROM V$SYSMETRIC_SUMMARY ORDER BY 2 DESC; -- V$SYSMETRIC: Contem metricas de sistema capturadas em 2 intervalos de tempo: ultimos 15 segundos ou ultimos 60 segundos. -- V$SYSMETRIC_SUMMARY: media ultima hora (ultimo snapshot) -- DBA_HIST_SYSMETRIC_SUMMARY: resumo da ultima semana --> depende de licenciamento do AWR
true
2833e4850e374c85625a855c8d4c2bac1f446fa7
SQL
jackylai87/messaging-api
/db/structure.sql
UTF-8
5,770
3.265625
3
[]
no_license
SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); SET check_function_bodies = false; SET xmloption = content; SET client_min_messages = warning; SET row_security = off; -- -- Name: pgcrypto; Type: EXTENSION; Schema: -; Owner: - -- CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; -- -- Name: EXTENSION pgcrypto; Type: COMMENT; Schema: -; Owner: - -- COMMENT ON EXTENSION pgcrypto IS 'cryptographic functions'; SET default_tablespace = ''; SET default_table_access_method = heap; -- -- Name: ar_internal_metadata; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.ar_internal_metadata ( key character varying NOT NULL, value character varying, created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL ); -- -- Name: conversations; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.conversations ( id uuid DEFAULT public.gen_random_uuid() NOT NULL, status character varying DEFAULT 'open'::character varying NOT NULL, platform character varying NOT NULL, created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL, user_id uuid, participant_id uuid NOT NULL ); -- -- Name: messages; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.messages ( id uuid DEFAULT public.gen_random_uuid() NOT NULL, "to" character varying NOT NULL, "from" character varying NOT NULL, message_type character varying NOT NULL, body text NOT NULL, twilio_response jsonb DEFAULT '{}'::jsonb NOT NULL, platform character varying NOT NULL, conversation_id uuid, created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL ); -- -- Name: participants; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.participants ( id uuid DEFAULT public.gen_random_uuid() NOT NULL, contact character varying NOT NULL, created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL ); -- -- Name: schema_migrations; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.schema_migrations ( version character varying NOT NULL ); -- -- Name: users; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.users ( id uuid DEFAULT public.gen_random_uuid() NOT NULL, email character varying NOT NULL, display_name character varying, password_digest character varying NOT NULL, created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL ); -- -- Name: ar_internal_metadata ar_internal_metadata_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.ar_internal_metadata ADD CONSTRAINT ar_internal_metadata_pkey PRIMARY KEY (key); -- -- Name: conversations conversations_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.conversations ADD CONSTRAINT conversations_pkey PRIMARY KEY (id); -- -- Name: messages messages_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.messages ADD CONSTRAINT messages_pkey PRIMARY KEY (id); -- -- Name: participants participants_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.participants ADD CONSTRAINT participants_pkey PRIMARY KEY (id); -- -- Name: schema_migrations schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.schema_migrations ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version); -- -- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.users ADD CONSTRAINT users_pkey PRIMARY KEY (id); -- -- Name: index_conversations_on_participant_id; Type: INDEX; Schema: public; Owner: - -- CREATE UNIQUE INDEX index_conversations_on_participant_id ON public.conversations USING btree (participant_id); -- -- Name: index_conversations_on_user_id; Type: INDEX; Schema: public; Owner: - -- CREATE INDEX index_conversations_on_user_id ON public.conversations USING btree (user_id); -- -- Name: index_messages_on_conversation_id; Type: INDEX; Schema: public; Owner: - -- CREATE INDEX index_messages_on_conversation_id ON public.messages USING btree (conversation_id); -- -- Name: index_participants_on_contact; Type: INDEX; Schema: public; Owner: - -- CREATE UNIQUE INDEX index_participants_on_contact ON public.participants USING btree (contact); -- -- Name: index_users_on_email; Type: INDEX; Schema: public; Owner: - -- CREATE UNIQUE INDEX index_users_on_email ON public.users USING btree (email); -- -- Name: conversations fk_rails_7c15d62a0a; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.conversations ADD CONSTRAINT fk_rails_7c15d62a0a FOREIGN KEY (user_id) REFERENCES public.users(id); -- -- Name: messages fk_rails_7f927086d2; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.messages ADD CONSTRAINT fk_rails_7f927086d2 FOREIGN KEY (conversation_id) REFERENCES public.conversations(id); -- -- Name: conversations fk_rails_d6a9ddc2a3; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.conversations ADD CONSTRAINT fk_rails_d6a9ddc2a3 FOREIGN KEY (participant_id) REFERENCES public.participants(id); -- -- PostgreSQL database dump complete -- SET search_path TO "$user", public; INSERT INTO "schema_migrations" (version) VALUES ('20201026100926'), ('20201026101904'), ('20201026102051'), ('20201027092315'), ('20201028041358');
true
1e8ea82fa16770d36c80e01bc987828dbcdcbe6f
SQL
smyers1243/multithread_2_2_update
/00_01_prep/Structure/005_KCLS_metabib_schema.sql
UTF-8
699
3
3
[]
no_license
DROP INDEX IF EXISTS metabib.normalized_author_field_entry_gist_trgm; DROP INDEX IF EXISTS metabib.normalized_remove_insignificants_author_field_entry_gist_trgm; DROP TYPE IF EXISTS metabib.field_entry_template CASCADE; CREATE TYPE metabib.field_entry_template AS ( field_class TEXT, field INT, facet_field BOOL, search_field BOOL, browse_field BOOL, source BIGINT, value TEXT ); CREATE TABLE metabib.browse_entry ( id BIGSERIAL PRIMARY KEY, value TEXT unique, index_vector tsvector ); CREATE INDEX metabib_browse_entry_index_vector_idx ON metabib.browse_entry USING GIN (index_vector);
true
5ca087eacaf695488f95f531fcabab17ae9ae3a5
SQL
romie1/mjd
/oracle/m2/s06.sql
UTF-8
181
3.25
3
[]
no_license
-- join on alter session set current_schema = hr; -- join-on, more flexible select region_name, country_name from regions r join countries c on r.region_id = c.region_id;
true
d66f8321bb4ff19db63afc59ab56432a566fcecc
SQL
chronic-care/preventive-care-ig
/input/cql/LungCancerSummary.cql
UTF-8
5,515
3.609375
4
[ "Apache-2.0" ]
permissive
library LungCancerSummary version '1.0.0' using FHIR version '4.0.1' include FHIRHelpers version '4.0.1' called FHIRHelpers include FHIRCommon version '4.0.1' called FC include PatientSummary called PS include LungCancerScreening called LCS codesystem "SNOMED": 'http://snomed.info/sct' code "Never Smoker": '266919005' from "SNOMED" context Patient define ScreeningSummary: { notifyPatient: "Notify Patient?", recommendScreening: "Recommend Screening?", name: 'Lung Cancer Screening', title: 'Should You Be Screened for Lung Cancer?', information: "Patient Information", decision: "Patient Decision", recommendation: "Patient Recommendation", questionnaire: 'mpc-lung-cancer' } define "Age 40 through 80": AgeInYears() >= 40 and AgeInYears() <= 80 // Notify patients starting at 40 (for pilot testing, may not keep in production). define "Notify Patient?": /* LCS."50 through 80" */ "Age 40 through 80" and (LCS."Is current smoker" or "Is former smoker") and not LCS."Has lung cancer" define "Recommend Screening?": LCS."Inclusion Criteria" define "Is former smoker": LCS."Former smoker observation" is not null define "Is former smoker who quit more than 15 years ago": (LCS."Former smoker observation" O where O.effective ends more than 15 years before Today() ) is not null define "Never smoker observation": LCS."Most recent smoking status observation" O where (O.value as CodeableConcept) ~ "Never Smoker" define "Is never smoker": "Never smoker observation" is not null define "Most recent chest CT procedure": Last(LCS."Chest CT procedure" P sort by (FHIRHelpers.ToDateTime(performed)) ) define "Smoking history in years": Round(duration in days of LCS."Smoking Period" / 365.25) define "Has less than 20 pack-year smoking history": LCS."Pack-years" < 20 '{Pack-years}' define "Packs per day": LCS."Most recent smoking status observation" O return singleton from (O.component C where C.code ~ LCS."PACKS A DAY").value.value as FHIR.decimal define "Smoking Status": if LCS."Is current smoker" then 'You are a current smoker.' else if LCS."Is former smoker who quit within past 15 years" then 'You are a former smoker who quit within the past 15 years.' else if "Is former smoker who quit more than 15 years ago" then 'You are a former smoker who quit more than 15 years ago.' else if "Is former smoker" then 'You are a former smoker with an unknown quit date.' else if "Is never smoker" then 'You have never smoked.' else 'Unknown smoking history.' /* define "Smoking History": if LCS."Pack-years" is not null then 'You have ' + ToString(LCS."Pack-years".value) + ' pack-years' + ' from ' + ToString(start of LCS."Smoking Period") + ' to ' + ToString(end of LCS."Smoking Period") + '.' else null */ define "Smoking History": if LCS."Pack-years" is not null then 'You smoked ' + ToString("Packs per day") + ' packs/day' + ' for ' + ToString("Smoking history in years") + ' years' + (if "Is former smoker" then ' ending in ' + ToString(year from end of LCS."Smoking Period") else '') + ', which equals ' + ToString(LCS."Pack-years".value) + ' pack years.' else null define "Patient Information": (List{ "Smoking Status", "Smoking History", (if exists LCS."Chest CT procedure" then 'Your last chest CT was on ' + ToString("Most recent chest CT procedure".performed) else null) }) Text where Text is not null define "Patient Decision": (List{ 'The guidelines recommend a low dose CT scan for people who currently smoke or are within 15 years of quitting smoking and have smoked for at least 20 pack years.' }) Text where Text is not null define "Patient Recommendation": (List{ (if "Recommend Screening?" then 'Consider Getting Screened for Lung Cancer' else if LCS."Pack-years" is null then 'Please complete your smoking history.' else 'You Don’t Need Lung Cancer Screening'), (if "Is former smoker who quit more than 15 years ago" then 'It is good you quit smoking in ' + Coalesce(ToString(year from end of LCS."Smoking Period"), 'an unknown year') +'. Don’t start smoking again.' else null), (if "Is former smoker" and "Has less than 20 pack-year smoking history" then 'It is good you quit smoking in ' + Coalesce(ToString(year from end of LCS."Smoking Period"), 'an unknown year') + ' and that you only have ' + ToString(LCS."Pack-years".value) + ' pack years of smoking' + '. Don’t start smoking again.' else null), (if LCS."Is current smoker" and "Has less than 20 pack-year smoking history" then 'It is good you only have ' + ToString(LCS."Pack-years".value) + ' pack years of smoking. This means you do not need lung cancer screening. But you should quit smoking before you damage your lungs and heart more.' else null), (if (LCS."Is current smoker" or "Is former smoker who quit more than 15 years ago") and LCS."Has 20 pack-year smoking history" then 'Lung cancer screening saves lives. Lung cancer is the leading cause of cancer death in the US. Most cases of lung cancer are caused by smoking. Lung cancer has a generally poor prognosis but if found early can be cured.' else null), (if LCS."Is current smoker" then 'Talk with ' + PS."Patient PCP name" + ' about how to help you quit smoking.' else null) }) Text where Text is not null
true
e8aba53cfb3c406430f4b6a831a6a9af31647095
SQL
William20160222/wang_jianghaonan_interactiveSVG
/data_info.sql
UTF-8
2,141
2.984375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: localhost:8889 -- Generation Time: Dec 06, 2019 at 04:51 AM -- Server version: 5.7.26 -- PHP Version: 7.3.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `db_fruit` -- -- -------------------------------------------------------- -- -- Table structure for table `data_info` -- CREATE TABLE `data_info` ( `ID` int(50) NOT NULL, `Name` varchar(20) NOT NULL, `Calories` varchar(10) NOT NULL, `Protein` varchar(10) NOT NULL, `Fiber` varchar(10) NOT NULL, `VitaminC` varchar(10) NOT NULL, `Iron` varchar(10) NOT NULL, `Fat` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `data_info` -- INSERT INTO `data_info` (`ID`, `Name`, `Calories`, `Protein`, `Fiber`, `VitaminC`, `Iron`, `Fat`) VALUES (1, 'Avocado', '322', '4.02g', '13.5g', '20.1mg', '1.11mg', '29.47g'), (2, 'Apple', '72', '0.36g', '3.3g', '6.3mg', '0.17mg', '0.23g'), (3, 'Banana', '105', '1.29g', '3.1g', '10.3mg', '0.31mg', '0.39g'), (4, 'Blueberry', '83', '1.07g', '3.5g', '14.1mg', '0.41mg', '0.48g'), (5, 'Coconut', '283', '2.66g', '7.2g', '2.6mg', '1.94mg', '26.79g'), (6, 'Dragon fruit', '60', '2g', '1g', '3mg', '1mg', '1.5g'), (7, 'Peach', '38', '0.89g', '1.5g', '6.5mg', '0.24mg', '0.24g'), (8, 'Pineapple', '74', '0.84g', '2.2g', '56.1mg', '0.43mg', '0.19g'); -- -- Indexes for dumped tables -- -- -- Indexes for table `data_info` -- ALTER TABLE `data_info` ADD PRIMARY KEY (`ID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `data_info` -- ALTER TABLE `data_info` MODIFY `ID` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
3d5371513dbae71c407e96c0ddfbdd3e9644c492
SQL
MUZakharov/TestDBRepo
/postgres/Views/information_schema.column_privileges.sql
UTF-8
3,974
3.53125
4
[]
no_license
SET SCHEMA "information_schema"; CREATE VIEW column_privileges AS SELECT (u_grantor.rolname)::sql_identifier AS grantor, (grantee.rolname)::sql_identifier AS grantee, (current_database())::sql_identifier AS table_catalog, (nc.nspname)::sql_identifier AS table_schema, (x.relname)::sql_identifier AS table_name, (x.attname)::sql_identifier AS column_name, (x.prtype)::character_data AS privilege_type, ( CASE WHEN (pg_has_role(x.grantee, x.relowner, 'USAGE'::text) OR x.grantable) THEN 'YES'::text ELSE 'NO'::text END)::yes_or_no AS is_grantable FROM ( SELECT pr_c.grantor, pr_c.grantee, a.attname, pr_c.relname, pr_c.relnamespace, pr_c.prtype, pr_c.grantable, pr_c.relowner FROM ( SELECT pg_class.oid, pg_class.relname, pg_class.relnamespace, pg_class.relowner, (aclexplode(COALESCE(pg_class.relacl, acldefault('r'::"char", pg_class.relowner)))).grantor AS grantor, (aclexplode(COALESCE(pg_class.relacl, acldefault('r'::"char", pg_class.relowner)))).grantee AS grantee, (aclexplode(COALESCE(pg_class.relacl, acldefault('r'::"char", pg_class.relowner)))).privilege_type AS privilege_type, (aclexplode(COALESCE(pg_class.relacl, acldefault('r'::"char", pg_class.relowner)))).is_grantable AS is_grantable FROM pg_class WHERE (pg_class.relkind = ANY (ARRAY['r'::"char", 'v'::"char", 'f'::"char"]))) pr_c(oid, relname, relnamespace, relowner, grantor, grantee, prtype, grantable), pg_attribute a WHERE (((a.attrelid = pr_c.oid) AND (a.attnum > 0)) AND (NOT a.attisdropped)) UNION SELECT pr_a.grantor, pr_a.grantee, pr_a.attname, c.relname, c.relnamespace, pr_a.prtype, pr_a.grantable, c.relowner FROM ( SELECT a.attrelid, a.attname, (aclexplode(COALESCE(a.attacl, acldefault('c'::"char", cc.relowner)))).grantor AS grantor, (aclexplode(COALESCE(a.attacl, acldefault('c'::"char", cc.relowner)))).grantee AS grantee, (aclexplode(COALESCE(a.attacl, acldefault('c'::"char", cc.relowner)))).privilege_type AS privilege_type, (aclexplode(COALESCE(a.attacl, acldefault('c'::"char", cc.relowner)))).is_grantable AS is_grantable FROM (pg_attribute a JOIN pg_class cc ON ((a.attrelid = cc.oid))) WHERE ((a.attnum > 0) AND (NOT a.attisdropped))) pr_a(attrelid, attname, grantor, grantee, prtype, grantable), pg_class c WHERE ((pr_a.attrelid = c.oid) AND (c.relkind = ANY (ARRAY['r'::"char", 'v'::"char", 'f'::"char"])))) x, pg_namespace nc, pg_authid u_grantor, ( SELECT pg_authid.oid, pg_authid.rolname FROM pg_authid UNION ALL SELECT (0)::oid AS oid, 'PUBLIC'::name) grantee(oid, rolname) WHERE (((((x.relnamespace = nc.oid) AND (x.grantee = grantee.oid)) AND (x.grantor = u_grantor.oid)) AND (x.prtype = ANY (ARRAY['INSERT'::text, 'SELECT'::text, 'UPDATE'::text, 'REFERENCES'::text]))) AND ((pg_has_role(u_grantor.oid, 'USAGE'::text) OR pg_has_role(grantee.oid, 'USAGE'::text)) OR (grantee.rolname = 'PUBLIC'::name))); ALTER TABLE information_schema.column_privileges OWNER TO postgres; -- -- Name: column_privileges; Type: ACL; Schema: information_schema; Owner: postgres -- REVOKE ALL ON TABLE column_privileges FROM PUBLIC; REVOKE ALL ON TABLE column_privileges FROM postgres; GRANT ALL ON TABLE column_privileges TO postgres; GRANT SELECT ON TABLE column_privileges TO PUBLIC;
true
be03de8624b6a65687635e9f24a2b0d13c5039bd
SQL
ivanceras/mockdata
/schema/exchange_rate.sql
UTF-8
695
3.125
3
[]
no_license
CREATE TABLE exchange_rate ( organization_id uuid, active boolean NOT NULL DEFAULT true, exchange_rate_id uuid NOT NULL DEFAULT uuid_generate_v4(), -- this will be referred when processing payments with different currencies from_currency uuid, exchange_rate double precision, to_currency uuid, created timestamp with time zone NOT NULL DEFAULT now(), created_by uuid, updated timestamp with time zone DEFAULT now(), updated_by uuid, priority double precision, info text, CONSTRAINT exchange_rate_id_pkey PRIMARY KEY (exchange_rate_id) ); COMMENT ON COLUMN exchange_rate.exchange_rate_id IS 'this will be referred when processing payments with different currencies';
true
9581cabfdf7dfafebad572d3d7b180574b97ca86
SQL
wx98/WeCharMark
/Service/WeCharMark_DataBase_SQL.sql
GB18030
731
3.359375
3
[ "Apache-2.0", "MIT" ]
permissive
create database WeCharMark_DataBase; use WeCharMark_DataBase; create table subjects ( sID int identity(1,1) primary key, sSubject varchar(128) ) create table students ( sNo varchar(32) primary key, sName varchar(32), sPass varchar(256) ) create table marks ( sNo varchar (32) not null foreign key references students (sNo) on delete cascade , sID int not null foreign key references subjects (sID) on delete cascade, mMark int , constraint mark_pk primary key (sNO,sID) ) insert into subjects(sSubject) values ('c#'),('NetWeb'),(''),('ѧӢ'),('ߵѧ'); insert into students (sNo,sName,sPass) values (123,'Admin',123),(0001,'wx',1234),(0002,'ph',1234),(0003,'zzb',1234),(0004,'wds',1234);
true
e9609939ae43f5ce774de9e77a85cc3c2afc1dde
SQL
mariam-hanna/rails_project
/hotels_rails .sql
UTF-8
5,554
3
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.0.6deb1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 22, 2014 at 06:45 AM -- Server version: 5.5.37-0ubuntu0.13.10.1 -- PHP Version: 5.5.3-1ubuntu2.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `hotels_rails` -- -- -------------------------------------------------------- -- -- Table structure for table `bookings` -- CREATE TABLE IF NOT EXISTS `bookings` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, `hotel_id` int(11) DEFAULT NULL, `room_id` int(11) DEFAULT NULL, `chkin` date DEFAULT NULL, `chkout` date DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ; -- -- Dumping data for table `bookings` -- INSERT INTO `bookings` (`id`, `user_id`, `hotel_id`, `room_id`, `chkin`, `chkout`, `created_at`, `updated_at`) VALUES (3, 1, 3, 4, '2014-05-01', '2014-05-02', '2014-05-21 19:06:55', '2014-05-21 19:06:55'), (5, 2, 3, 4, '2014-05-03', '2014-05-04', '2014-05-21 19:38:41', '2014-05-21 19:38:41'), (6, 2, 3, 5, '2014-05-05', '2014-05-06', '2014-05-21 19:53:23', '2014-05-21 19:53:23'), (18, 2, 3, 4, '2014-05-09', '2014-05-10', '2014-05-21 20:13:04', '2014-05-21 20:13:04'); -- -------------------------------------------------------- -- -- Table structure for table `comments` -- CREATE TABLE IF NOT EXISTS `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, `user_name` varchar(255) NOT NULL, `hotel_id` int(11) DEFAULT NULL, `room_id` int(11) DEFAULT NULL, `comment` varchar(255) DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=25 ; -- -- Dumping data for table `comments` -- INSERT INTO `comments` (`id`, `user_id`, `user_name`, `hotel_id`, `room_id`, `comment`, `created_at`, `updated_at`) VALUES (23, 1, 'mariam1', 3, 4, 'mariam', '2014-05-22 06:01:26', '2014-05-22 06:01:26'), (24, 2, 'admin', 3, 5, 'admin', '2014-05-22 06:01:53', '2014-05-22 06:01:53'); -- -------------------------------------------------------- -- -- Table structure for table `hotels` -- CREATE TABLE IF NOT EXISTS `hotels` ( `id` int(11) NOT NULL AUTO_INCREMENT, `country` varchar(255) DEFAULT NULL, `city` varchar(255) DEFAULT NULL, `region` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, `phone` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `hotels` -- INSERT INTO `hotels` (`id`, `country`, `city`, `region`, `name`, `address`, `phone`) VALUES (3, 'Egypt', 'Alex', 'san stefano', 'hotel1', 'ay 7ta', '1234'), (4, 'Egypt', 'Alex', 'Moharm Bek', 'hotel2', 'ay 7ta', '1234'); -- -------------------------------------------------------- -- -- Table structure for table `rooms` -- CREATE TABLE IF NOT EXISTS `rooms` ( `id` int(11) NOT NULL AUTO_INCREMENT, `hotel_id` int(11) DEFAULT NULL, `room_price` int(11) DEFAULT NULL, `img` varchar(255) DEFAULT NULL, `reserved` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `hotel_id` (`hotel_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ; -- -- Dumping data for table `rooms` -- INSERT INTO `rooms` (`id`, `hotel_id`, `room_price`, `img`, `reserved`) VALUES (4, 3, 122, '/assets/room1.jpg', 0), (5, 3, 123, '/assets/room2.jpg', 0), (6, 4, 1000, '/assets/room3.jpg', 0), (7, 4, 123, '/assets/room4.jpg', 0); -- -------------------------------------------------------- -- -- Table structure for table `schema_migrations` -- CREATE TABLE IF NOT EXISTS `schema_migrations` ( `version` varchar(255) NOT NULL, UNIQUE KEY `unique_schema_migrations` (`version`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `schema_migrations` -- INSERT INTO `schema_migrations` (`version`) VALUES ('20140520090642'), ('20140520090716'), ('20140520090804'), ('20140521185450'), ('20140521212127'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `phone` varchar(255) DEFAULT NULL, `admin` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `index_users_on_email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `password`, `phone`, `admin`) VALUES (1, 'mariam1', 'mariam1@yahoo.com', '8ca6342915ac81dd2d3eec49e2098db9', '1234', 0), (2, 'admin', 'admin@yahoo.com', '8ca6342915ac81dd2d3eec49e2098db9', '1234', 1), (4, 'mariam2', 'mariam2@yahoo.com', '8ca6342915ac81dd2d3eec49e2098db9', '1234', 0); -- -- Constraints for dumped tables -- -- -- Constraints for table `rooms` -- ALTER TABLE `rooms` ADD CONSTRAINT `rooms_ibfk_1` FOREIGN KEY (`hotel_id`) REFERENCES `hotels` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
7de6fa1d12d01332c5aa0805b36a2c547970d281
SQL
silence-do-good/stress-test-Postgres-and-MySQL
/dump/high/day11/select1717.sql
UTF-8
178
2.625
3
[]
no_license
SELECT timeStamp, temperature FROM ThermometerOBSERVATION o WHERE timestamp>'2017-11-10T17:17:00Z' AND timestamp<'2017-11-11T17:17:00Z' AND temperature>=46 AND temperature<=81
true
546d9e6452b031e0dd6123d83a71a7efe6ce93d8
SQL
Rahul2200289/SQL-Databases
/Morgan Importing Database/SQLQuery6.sql
UTF-8
425
3.34375
3
[]
no_license
CREATE TABLE SHIPMENT ( ShipmentID int identity (100,1), ShipperID INT, PurchasingAgentID INT not NULL, ShipperInvoiceNumber INT, Origin VARCHAR (20), Destination VARCHAR (20), ScheduledDepartureDate DATE, ActualDepartureDate DATE, EstimatedArrivalDate DATE, Constraint pk6 primary key(ShipmentID), Constraint fk2 foreign key(ShipperID) references SHIPPER(ShipperID) ON DELETE CASCADE ON UPDATE CASCADE )
true
a4f4b3d82d5b4adc6d7c7b9c5f2782f670dbb1e9
SQL
etudiant99/pneus
/scripts/wp_inv_type.sql
UTF-8
1,559
3.015625
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.1.14 -- http://www.phpmyadmin.net -- -- Client : 127.0.0.1 -- Généré le : Sam 24 Mars 2018 à 20:36 -- Version du serveur : 5.6.17 -- Version de PHP : 5.5.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Base de données : `denis` -- -- -------------------------------------------------------- -- -- Structure de la table `wp_inv_type` -- CREATE TABLE IF NOT EXISTS `wp_inv_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; -- -- Contenu de la table `wp_inv_type` -- INSERT INTO `wp_inv_type` (`id`, `type`) VALUES (1, '2 Dr Convertible'), (2, '2 Dr Coupe'), (3, '2 Dr Hearse'), (4, '4 Dr Limousine'), (5, '4 Dr Sedan'), (7, '2 Dr Hardtop'), (8, '2 Dr Sedan'), (9, '3 Dr. Hatchback'), (10, 'Base (155-R15)'), (11, '4 Dr Hardtop'), (12, '4 Dr Wagon'), (13, '2 Dr Wagon'), (14, '5 Dr Wagon'), (15, '2 Dr Standard Cab Pickup'), (16, '2 Dr Hatchback'), (17, '3 Dr Standard Passenger'), (18, '4 Dr Sport Utility'), (19, '2 Dr Cab & Chassis'); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
cdedb8597933d7695229734006beff9f15987bdb
SQL
baoxingwang/sql-challenge
/EmployeeSQL/SQLcode.sql
UTF-8
3,520
4.5
4
[]
no_license
-------------------------------------- --Build database CREATE TABLE departments ( dept_no VARCHAR PRIMARY KEY, dept_name VARCHAR ); CREATE TABLE employees ( emp_no VARCHAR PRIMARY KEY, birth_date VARCHAR, first_name VARCHAR, last_name VARCHAR, gender VARCHAR, hire_data VARCHAR ); CREATE TABLE dept_emp ( emp_no VARCHAR NOT NULL REFERENCES employees(emp_no), dept_no VARCHAR NOT NULL REFERENCES departments(dept_no), PRIMARY KEY (emp_no, dept_no), from_date VARCHAR, to_date VARCHAR ); -- SELECT * FROM departments; CREATE TABLE dept_manager( dept_no VARCHAR NOT NULL REFERENCES departments(dept_no), emp_no VARCHAR NOT NULL REFERENCES employees(emp_no), PRIMARY KEY (emp_no, dept_no), from_date VARCHAR, to_date VARCHAR ); -- DROP TABLE dept_manager; -- SELECT * FROM dept_manager; CREATE TABLE salaries ( emp_no VARCHAR PRIMARY KEY NOT NULL REFERENCES employees(emp_no), salary INTEGER, from_date VARCHAR, to_date VARCHAR ); CREATE TABLE titles ( emp_no VARCHAR REFERENCES employees(emp_no), title VARCHAR, from_date VARCHAR, to_date VARCHAR ); -- ALTER TABLE titles -- ADD COLUMN emp_no VARCHAR REFERENCES employees(emp_no); -- SELECT * FROM titles; -- DROP TABLE titles; -- select titles.title, employees.first_name -- from employees -- left join titles on employees.emp_no = titles.emp_no ; ------------------------------------------------------------------- --Question 1 SELECT employees.emp_no, first_name, last_name, gender, salary FROM employees INNER JOIN salaries ON employees.emp_no = salaries.emp_no; -- SELECT count(*) FROM employees; -- SELECT count(*) FROM salaries; -- SELECT count(*) FROM titles; -- SELECT * FROM employees; ----------------------------------- --Question 2 SELECT * FROM employees WHERE hire_data LIKE '%1986%' ; -- SELECT * FROM dept_manager; -- SELECT * FROM departments; ------------------------------------------------- --Question3 SELECT dept_manager.dept_no, departments.dept_name, dept_manager.emp_no, first_name, last_name, dept_manager.from_date, dept_manager.to_date FROM dept_manager INNER JOIN departments ON departments.dept_no = dept_manager.dept_no INNER JOIN employees ON dept_manager.emp_no = employees.emp_no ; ------------------------------------------------------- --Question 4 SELECT e.emp_no, last_name, first_name, dept_name FROM departments AS d INNER JOIN dept_emp AS de ON de.dept_no = d.dept_no INNER JOIN employees AS e ON e.emp_no = de.emp_no; -------------------------------------------------------------- --Question 5 SELECT * FROM employees WHERE first_name = 'Hercules' AND last_name LIKE 'B%' ; ------------------------------------------- --Question 6 SELECT e.emp_no, e.last_name, e.first_name,d.dept_name FROM dept_emp AS d_e INNER JOIN employees AS e ON d_e.emp_no = e.emp_no INNER JOIN departments AS d ON d_e.dept_no = d.dept_no WHERE d.dept_name = 'Sales'; ------------------------------------------------- --Question 7 SELECT e.emp_no, e.last_name, e.first_name,d.dept_name FROM dept_emp AS d_e INNER JOIN employees AS e ON d_e.emp_no = e.emp_no INNER JOIN departments AS d ON d_e.dept_no = d.dept_no WHERE d.dept_name = 'Sales' OR d.dept_name = 'Development'; ------------------------------------------------- --Question 8 SELECT last_name, count(last_name) AS name_frequency FROM employees AS e GROUP BY last_name ORDER BY name_frequency DESC ------------------ SELECT t.title,s.salary FROM "salaries" AS s INNER JOIN "titles" AS t ON t.emp_no = s.emp_no;
true
8781d45916f417eeb739ce0a58f64a7e799d92ea
SQL
NicoCPH/Carport
/Database/carportdb_forespoergsel.sql
UTF-8
4,720
2.953125
3
[]
no_license
-- MySQL dump 10.13 Distrib 8.0.19, for Win64 (x86_64) -- -- Host: 127.0.0.1 Database: carportdb -- ------------------------------------------------------ -- Server version 8.0.19 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!50503 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `forespoergsel` -- DROP TABLE IF EXISTS `forespoergsel`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `forespoergsel` ( `idforespoergsel` int NOT NULL AUTO_INCREMENT, `carportlaengde` int NOT NULL, `carportbredde` int NOT NULL, `carportfarve` int NOT NULL, `carporttraetype` int NOT NULL, `tagmateriale` int NOT NULL, `taghaeldning` int NOT NULL, `redskabsrumbredde` int DEFAULT NULL, `redskabsrumlaengde` int DEFAULT NULL, `redskabsrumbeklaedningstype` int DEFAULT NULL, `redskabsrumgulv` int DEFAULT NULL, `kundeID` int NOT NULL, `pris` double DEFAULT NULL, PRIMARY KEY (`idforespoergsel`), KEY `fk_carport_bredde_idx` (`carportbredde`), KEY `fk_carport_laengde_idx` (`carportlaengde`), KEY `fk_carport_farve_idx` (`carportfarve`), KEY `fk_carport_traetype_idx` (`carporttraetype`), KEY `fk_tag_materiale_idx` (`tagmateriale`), KEY `fk_tag_haeldning_idx` (`taghaeldning`), KEY `fk_redskabsrum_bredde_idx` (`redskabsrumbredde`), KEY `fk_redskabsrum_laengde_idx` (`redskabsrumlaengde`), KEY `fk_redskabsrum_beklaedningstype_idx` (`redskabsrumbeklaedningstype`), KEY `fk_kundeID_idx` (`kundeID`), KEY `fk_kunde_Id_idx` (`kundeID`), KEY `fkadl_idx` (`kundeID`), KEY `fk_gulv_idx` (`redskabsrumgulv`), CONSTRAINT `fk_carport_bredde` FOREIGN KEY (`carportbredde`) REFERENCES `bredder` (`idbredder`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_carport_farve` FOREIGN KEY (`carportfarve`) REFERENCES `farver` (`idfarver`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_carport_laengde` FOREIGN KEY (`carportlaengde`) REFERENCES `laengder` (`idlaengder`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_carport_traetype` FOREIGN KEY (`carporttraetype`) REFERENCES `traetyper` (`idtraetyper`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_gulv` FOREIGN KEY (`redskabsrumgulv`) REFERENCES `gulv` (`idGulv`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_kundeid` FOREIGN KEY (`kundeID`) REFERENCES `kunde` (`kundeId`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_redskabsrum_beklaedningstype` FOREIGN KEY (`redskabsrumbeklaedningstype`) REFERENCES `traetyper` (`idtraetyper`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_redskabsrum_bredde` FOREIGN KEY (`redskabsrumbredde`) REFERENCES `bredder` (`idbredder`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_redskabsrum_laengde` FOREIGN KEY (`redskabsrumlaengde`) REFERENCES `laengder` (`idlaengder`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_tag_haeldning` FOREIGN KEY (`taghaeldning`) REFERENCES `haeldning` (`idhaeldning`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_tag_materiale` FOREIGN KEY (`tagmateriale`) REFERENCES `tagmateriale` (`idtagmateriale`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `forespoergsel` -- LOCK TABLES `forespoergsel` WRITE; /*!40000 ALTER TABLE `forespoergsel` DISABLE KEYS */; INSERT INTO `forespoergsel` VALUES (25,21,19,1,1,16,8,1,1,1,1,14,15437.5),(26,21,19,1,1,16,8,1,1,1,1,15,14582),(27,21,19,1,1,16,8,1,1,1,1,15,15437.5),(28,21,19,1,1,16,8,1,1,1,1,15,15437.5),(29,21,19,1,1,16,8,20,22,7,4,15,14437.5); /*!40000 ALTER TABLE `forespoergsel` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-05-20 11:28:49
true
df98097062d315d1d266162317249b62201e9eb3
SQL
encolpius1965/gloss
/sql_proc/TmpPasswordApply.sql
UTF-8
607
2.875
3
[]
no_license
CREATE DEFINER=`root`@`%` PROCEDURE `TmpPasswordApply`( __password varchar(255), __email varchar(255), lMsg tinyint ) BEGIN SET @UserId = (SELECT USER_ID FROM USER WHERE EMAIL=__email); SET @login = (SELECT LOGIN FROM USER WHERE EMAIL=__email); if ( @UserId>0) then CALL UpdateUserInstall(@UserId, @login, __password, __email); if ( lMsg>0) then INSERT INTO USMESS (USER_ID, LTYPE, TXT) VALUES (@UserId, -1, 'To '+ __email + ': Логин '+ @login+' Новый пароль '+ __password); end if; end if; END
true
f8c6feba80a2986c10c64c5d0a451830cc7aadff
SQL
Khalll/shifting
/shifting.sql
UTF-8
5,035
3.109375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Sep 01, 2018 at 03:36 PM -- Server version: 10.1.19-MariaDB -- PHP Version: 7.0.13 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `shifting` -- -- -------------------------------------------------------- -- -- Table structure for table `jadwal_shifting` -- CREATE TABLE `jadwal_shifting` ( `id` int(11) NOT NULL, `id_pengajuan` int(11) NOT NULL, `minggu` int(11) NOT NULL, `tanggal_1` date NOT NULL, `tanggal_2` date NOT NULL, `jadwal` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `mhs` -- CREATE TABLE `mhs` ( `nim` varchar(50) NOT NULL, `nama` varchar(50) NOT NULL, `prodi` int(11) NOT NULL, `semester` int(11) NOT NULL, `password` varchar(50) NOT NULL, `tahun_masuk` varchar(10) NOT NULL, `user_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `mhs` -- INSERT INTO `mhs` (`nim`, `nama`, `prodi`, `semester`, `password`, `tahun_masuk`, `user_id`) VALUES ('3311612001', 'Ferdinand R Tarigan', 1, 4, '202cb962ac59075b964b07152d234b70', '', 0), ('3311612002', 'Rizki Khalil', 1, 4, '202cb962ac59075b964b07152d234b70', '', 0); -- -------------------------------------------------------- -- -- Table structure for table `pengajuan` -- CREATE TABLE `pengajuan` ( `id_pengajuan` int(11) NOT NULL, `tanggal` date NOT NULL, `nim` varchar(50) NOT NULL, `status` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `prodi` -- CREATE TABLE `prodi` ( `id` int(11) NOT NULL, `jurusan` varchar(50) NOT NULL, `nama_prodi` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `prodi` -- INSERT INTO `prodi` (`id`, `jurusan`, `nama_prodi`) VALUES (1, 'Teknik Informatika', 'Informatika'), (2, 'Teknik Informatika', 'Informatika'), (3, 'Manajemen', 'Akutansi'), (4, 'Teknik', 'Mesin'); -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `user_id` int(11) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `hak_akses` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `user_detail` -- CREATE TABLE `user_detail` ( `detail_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `nama` varchar(30) NOT NULL, `alamat` varchar(30) NOT NULL, `no_telp` varchar(15) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `jadwal_shifting` -- ALTER TABLE `jadwal_shifting` ADD PRIMARY KEY (`id`), ADD KEY `id_pengajuan` (`id_pengajuan`); -- -- Indexes for table `mhs` -- ALTER TABLE `mhs` ADD PRIMARY KEY (`nim`), ADD KEY `prodi` (`prodi`); -- -- Indexes for table `pengajuan` -- ALTER TABLE `pengajuan` ADD PRIMARY KEY (`id_pengajuan`), ADD KEY `nim` (`nim`); -- -- Indexes for table `prodi` -- ALTER TABLE `prodi` ADD PRIMARY KEY (`id`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`user_id`); -- -- Indexes for table `user_detail` -- ALTER TABLE `user_detail` ADD PRIMARY KEY (`detail_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `jadwal_shifting` -- ALTER TABLE `jadwal_shifting` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `prodi` -- ALTER TABLE `prodi` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `user_detail` -- ALTER TABLE `user_detail` MODIFY `detail_id` int(11) NOT NULL AUTO_INCREMENT; -- -- Constraints for dumped tables -- -- -- Constraints for table `jadwal_shifting` -- ALTER TABLE `jadwal_shifting` ADD CONSTRAINT `jadwal_shifting_ibfk_1` FOREIGN KEY (`id_pengajuan`) REFERENCES `pengajuan` (`id_pengajuan`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `mhs` -- ALTER TABLE `mhs` ADD CONSTRAINT `mhs_ibfk_1` FOREIGN KEY (`prodi`) REFERENCES `prodi` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `pengajuan` -- ALTER TABLE `pengajuan` ADD CONSTRAINT `pengajuan_ibfk_1` FOREIGN KEY (`nim`) REFERENCES `mhs` (`nim`) ON DELETE CASCADE ON UPDATE CASCADE; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
ebf02f33ddf3bc403e212417486d7317b35420c1
SQL
marciioluucas/superfox
/superfox.sql
UTF-8
15,492
2.953125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 28-Nov-2016 às 23:03 -- Versão do servidor: 10.1.16-MariaDB -- PHP Version: 7.0.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `superfox` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `cargo` -- CREATE TABLE `cargo` ( `pk_cargo` int(11) NOT NULL, `nome` varchar(150) NOT NULL, `descricao` text, `ativado` tinyint(1) NOT NULL DEFAULT '1', `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `cargo` -- INSERT INTO `cargo` (`pk_cargo`, `nome`, `descricao`, `ativado`, `data_cadastro`, `data_ultima_alteracao`) VALUES (1, 'teste', 'teste', 1, '0000-00-00', NULL), (2, 'Repositor', 'Repoe os produtos na prateleira', 1, '0000-00-00', NULL), (3, 'Gerente', 'Gerencia as dependencias do mercado', 1, '0000-00-00', NULL), (4, 'Caixa', 'Passa as compras dos clientes e cadastra as vendas.', 1, '0000-00-00', NULL), (5, 'Vendedô de cremosin', '423423', 0, '0000-00-00', '2016-11-18'), (7, 'Dorama', 'efdhfgghb', 1, '0000-00-00', '0000-00-00'), (10, 'asdasddt', '423423', 1, '0000-00-00', '0000-00-00'); -- -------------------------------------------------------- -- -- Estrutura da tabela `categoria` -- CREATE TABLE `categoria` ( `pk_categoria` int(11) NOT NULL, `nome` varchar(180) NOT NULL, `descricao` text, `fk_produto` int(11) NOT NULL, `ativado` tinyint(1) NOT NULL DEFAULT '1', `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `cliente` -- CREATE TABLE `cliente` ( `pk_cliente` int(11) NOT NULL, `nome` varchar(180) NOT NULL, `cpf_cnpj` varchar(45) DEFAULT NULL, `telefone` varchar(45) DEFAULT NULL, `fk_cliente_endereco` int(11) NOT NULL, `ativado` tinyint(1) NOT NULL DEFAULT '1', `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `cliente_endereco` -- CREATE TABLE `cliente_endereco` ( `pk_cliente_endereco` int(11) NOT NULL, `cidade` varchar(80) NOT NULL, `estado` varchar(2) NOT NULL, `rua` varchar(100) NOT NULL, `setor` varchar(100) NOT NULL, `logradouro` varchar(100) NOT NULL, `cep` varchar(45) NOT NULL, `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `compra` -- CREATE TABLE `compra` ( `pk_compra` int(11) NOT NULL, `valor` float(10,2) NOT NULL, `data_cadastro` date NOT NULL, `hora_cadastro` time NOT NULL, `ativado` tinyint(1) NOT NULL DEFAULT '1', `data_ultima_alteracao` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `compra` -- INSERT INTO `compra` (`pk_compra`, `valor`, `data_cadastro`, `hora_cadastro`, `ativado`, `data_ultima_alteracao`) VALUES (1, 200.00, '0000-00-00', '00:00:11', 1, NULL); -- -------------------------------------------------------- -- -- Estrutura da tabela `fornecedor` -- CREATE TABLE `fornecedor` ( `pk_fornecedor` int(11) NOT NULL, `nome_empresarial` varchar(180) NOT NULL, `nome_fantasia` varchar(180) DEFAULT NULL, `cpf_cnpj` varchar(45) NOT NULL, `ramo` varchar(45) NOT NULL, `representante` varchar(180) NOT NULL, `mei` tinyint(1) NOT NULL DEFAULT '0', `ativado` tinyint(1) NOT NULL DEFAULT '1', `data_ultima_alteracao` date DEFAULT NULL, `data_cadastro` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `fornecedor_endereco` -- CREATE TABLE `fornecedor_endereco` ( `pk_fornecedor_endereco` int(11) NOT NULL, `fk_fornecedor` int(11) NOT NULL, `cidade` varchar(80) NOT NULL, `estado` varchar(2) NOT NULL, `rua` varchar(100) NOT NULL, `setor` varchar(100) NOT NULL, `logradouro` varchar(100) NOT NULL, `cep` varchar(45) NOT NULL, `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `funcionario` -- CREATE TABLE `funcionario` ( `pk_funcionario` int(11) NOT NULL, `nome` varchar(180) NOT NULL, `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL, `fk_cargo` int(11) NOT NULL, `cpf` varchar(45) NOT NULL, `ativado` tinyint(1) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `funcionario` -- INSERT INTO `funcionario` (`pk_funcionario`, `nome`, `data_cadastro`, `data_ultima_alteracao`, `fk_cargo`, `cpf`, `ativado`) VALUES (1, 'Márcio Lucas', '2016-10-21', NULL, 3, '03794335163', 1), (2, 'Marco Aurélio', '2016-10-21', NULL, 2, '12345678912', 1), (3, 'João Victor', '2016-10-21', NULL, 4, '12545681351', 1), (4, 'Juanes Adriano', '2016-10-21', NULL, 2, '65481256613', 1), (5, 'Oto Gloria', '2016-10-21', NULL, 3, '45848979815', 1), (6, 'Sadrak', '2016-10-21', NULL, 4, '51468487841', 1); -- -------------------------------------------------------- -- -- Estrutura da tabela `itens_compra` -- CREATE TABLE `itens_compra` ( `fk_produto` int(11) NOT NULL, `quantidade` int(11) NOT NULL, `fk_compra` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Acionadores `itens_compra` -- DELIMITER $$ CREATE TRIGGER `itens_compra_AFTER_DELETE` AFTER DELETE ON `itens_compra` FOR EACH ROW BEGIN UPDATE produto SET estoque = estoque - OLD.quantidade WHERE pk_produto = OLD.fk_produto; END $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `itens_compra_AFTER_INSERT` AFTER INSERT ON `itens_compra` FOR EACH ROW BEGIN UPDATE produto SET estoque = estoque + NEW.quantidade WHERE pk_produto = NEW.fk_produto; END $$ DELIMITER ; -- -------------------------------------------------------- -- -- Estrutura da tabela `itens_venda` -- CREATE TABLE `itens_venda` ( `fk_produto` int(11) NOT NULL, `quantidade` int(11) NOT NULL, `fk_venda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Acionadores `itens_venda` -- DELIMITER $$ CREATE TRIGGER `itens_venda_AFTER_DELETE` AFTER DELETE ON `itens_venda` FOR EACH ROW BEGIN UPDATE produto SET estoque = estoque + OLD.quantidade WHERE pk_produto = OLD.fk_produto; END $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `itens_venda_AFTER_INSERT` AFTER INSERT ON `itens_venda` FOR EACH ROW BEGIN UPDATE produto SET estoque = estoque - NEW.quantidade WHERE pk_produto = NEW.fk_produto; END $$ DELIMITER ; -- -------------------------------------------------------- -- -- Estrutura da tabela `produto` -- CREATE TABLE `produto` ( `pk_produto` int(11) NOT NULL, `codigo_de_barras` int(15) NOT NULL, `nome` varchar(100) NOT NULL, `marca` varchar(45) DEFAULT NULL, `lote` varchar(45) NOT NULL, `validade` varchar(40) NOT NULL, `fabricacao` varchar(40) NOT NULL, `preco` float(10,2) NOT NULL, `estoque` int(11) NOT NULL, `estoque_minimo` int(11) NOT NULL, `ativado` tinyint(1) NOT NULL DEFAULT '1', `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `produto` -- INSERT INTO `produto` (`pk_produto`, `codigo_de_barras`, `nome`, `marca`, `lote`, `validade`, `fabricacao`, `preco`, `estoque`, `estoque_minimo`, `ativado`, `data_cadastro`, `data_ultima_alteracao`) VALUES (1, 123456789, 'teste1', 'marcateste1', 'lotet1', '11-11-2011', '11-11-2011', 1.00, 10, 2, 1, '0000-00-00', NULL), (2, 546456489, 'teste2', 'marcateste2', 'lotet2', '11-11-2011', '11-11-2011', 2.00, 90, 3, 1, '0000-00-00', NULL); -- -------------------------------------------------------- -- -- Estrutura da tabela `usuario` -- CREATE TABLE `usuario` ( `pk_usuario` int(11) NOT NULL, `login` varchar(32) NOT NULL, `senha` varchar(32) NOT NULL, `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL, `email` varchar(180) DEFAULT NULL, `ativado` tinyint(1) NOT NULL DEFAULT '1', `fk_funcionario` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `usuario` -- INSERT INTO `usuario` (`pk_usuario`, `login`, `senha`, `data_cadastro`, `data_ultima_alteracao`, `email`, `ativado`, `fk_funcionario`) VALUES (23, 'marciioluucas', '123456', '2016-10-27', '0000-00-00', 'marciioluucas@gmail.com', 1, 1), (24, 'marco.aurelio', '123', '2016-10-28', NULL, 'kbral99@gmail.com', 1, 2), (25, 'joao.victor', '123', '2016-10-28', NULL, 'joaogarciafirmino@gmail.com', 1, 3), (26, 'juanes-adriano', '123', '2016-10-28', NULL, 'juaneshtk50@gmail.com', 1, 4), (27, 'oto.gloria', '123', '2016-10-28', NULL, 'otogloria@gmail.com', 1, 5), (28, 'sadrak', '123', '2016-10-28', NULL, 'sadrakss@outlook.com', 1, 6); -- -------------------------------------------------------- -- -- Estrutura da tabela `venda` -- CREATE TABLE `venda` ( `pk_venda` int(11) NOT NULL, `valor` float(10,2) NOT NULL, `data` date NOT NULL, `hora` time NOT NULL, `fk_usuario` int(11) NOT NULL, `ativado` tinyint(1) NOT NULL, `data_cadastro` date NOT NULL, `data_ultima_alteracao` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `cargo` -- ALTER TABLE `cargo` ADD PRIMARY KEY (`pk_cargo`); -- -- Indexes for table `categoria` -- ALTER TABLE `categoria` ADD PRIMARY KEY (`pk_categoria`,`fk_produto`), ADD KEY `fk_categoria_produto_idx` (`fk_produto`); -- -- Indexes for table `cliente` -- ALTER TABLE `cliente` ADD PRIMARY KEY (`pk_cliente`,`fk_cliente_endereco`), ADD KEY `fk_cliente_cliente_endereco1_idx` (`fk_cliente_endereco`); -- -- Indexes for table `cliente_endereco` -- ALTER TABLE `cliente_endereco` ADD PRIMARY KEY (`pk_cliente_endereco`); -- -- Indexes for table `compra` -- ALTER TABLE `compra` ADD PRIMARY KEY (`pk_compra`); -- -- Indexes for table `fornecedor` -- ALTER TABLE `fornecedor` ADD PRIMARY KEY (`pk_fornecedor`); -- -- Indexes for table `fornecedor_endereco` -- ALTER TABLE `fornecedor_endereco` ADD PRIMARY KEY (`pk_fornecedor_endereco`,`fk_fornecedor`), ADD KEY `fk_fornecedor_endereco_fornecedor_idx` (`fk_fornecedor`); -- -- Indexes for table `funcionario` -- ALTER TABLE `funcionario` ADD PRIMARY KEY (`pk_funcionario`), ADD KEY `fk_funcionario_cargo1_idx` (`fk_cargo`); -- -- Indexes for table `itens_compra` -- ALTER TABLE `itens_compra` ADD PRIMARY KEY (`fk_produto`,`fk_compra`), ADD KEY `fk_produto_has_compra_produto1_idx` (`fk_produto`), ADD KEY `fk_itens_compra_compra2_idx` (`fk_compra`); -- -- Indexes for table `itens_venda` -- ALTER TABLE `itens_venda` ADD PRIMARY KEY (`fk_produto`,`fk_venda`), ADD KEY `fk_produto_has_venda_produto1_idx` (`fk_produto`), ADD KEY `fk_itens_venda_venda1_idx` (`fk_venda`); -- -- Indexes for table `produto` -- ALTER TABLE `produto` ADD PRIMARY KEY (`pk_produto`); -- -- Indexes for table `usuario` -- ALTER TABLE `usuario` ADD PRIMARY KEY (`pk_usuario`,`fk_funcionario`), ADD KEY `fk_usuario_funcionario1_idx` (`fk_funcionario`); -- -- Indexes for table `venda` -- ALTER TABLE `venda` ADD PRIMARY KEY (`pk_venda`,`fk_usuario`), ADD KEY `fk_venda_table11_idx` (`fk_usuario`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `cargo` -- ALTER TABLE `cargo` MODIFY `pk_cargo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT for table `cliente` -- ALTER TABLE `cliente` MODIFY `pk_cliente` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `cliente_endereco` -- ALTER TABLE `cliente_endereco` MODIFY `pk_cliente_endereco` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `compra` -- ALTER TABLE `compra` MODIFY `pk_compra` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `fornecedor` -- ALTER TABLE `fornecedor` MODIFY `pk_fornecedor` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `fornecedor_endereco` -- ALTER TABLE `fornecedor_endereco` MODIFY `pk_fornecedor_endereco` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `funcionario` -- ALTER TABLE `funcionario` MODIFY `pk_funcionario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `produto` -- ALTER TABLE `produto` MODIFY `pk_produto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `usuario` -- ALTER TABLE `usuario` MODIFY `pk_usuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=29; -- -- AUTO_INCREMENT for table `venda` -- ALTER TABLE `venda` MODIFY `pk_venda` int(11) NOT NULL AUTO_INCREMENT; -- -- Constraints for dumped tables -- -- -- Limitadores para a tabela `categoria` -- ALTER TABLE `categoria` ADD CONSTRAINT `fk_categoria_produto` FOREIGN KEY (`fk_produto`) REFERENCES `produto` (`pk_produto`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Limitadores para a tabela `cliente` -- ALTER TABLE `cliente` ADD CONSTRAINT `fk_cliente_cliente_endereco1` FOREIGN KEY (`fk_cliente_endereco`) REFERENCES `cliente_endereco` (`pk_cliente_endereco`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Limitadores para a tabela `fornecedor_endereco` -- ALTER TABLE `fornecedor_endereco` ADD CONSTRAINT `fk_fornecedor_endereco_fornecedor` FOREIGN KEY (`fk_fornecedor`) REFERENCES `fornecedor` (`pk_fornecedor`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Limitadores para a tabela `funcionario` -- ALTER TABLE `funcionario` ADD CONSTRAINT `fk_funcionario_cargo1` FOREIGN KEY (`fk_cargo`) REFERENCES `cargo` (`pk_cargo`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Limitadores para a tabela `itens_compra` -- ALTER TABLE `itens_compra` ADD CONSTRAINT `fk_itens_compra_compra2` FOREIGN KEY (`fk_compra`) REFERENCES `compra` (`pk_compra`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_produto_has_compra_produto1` FOREIGN KEY (`fk_produto`) REFERENCES `produto` (`pk_produto`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Limitadores para a tabela `itens_venda` -- ALTER TABLE `itens_venda` ADD CONSTRAINT `fk_itens_venda_venda1` FOREIGN KEY (`fk_venda`) REFERENCES `venda` (`pk_venda`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_produto_has_venda_produto1` FOREIGN KEY (`fk_produto`) REFERENCES `produto` (`pk_produto`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Limitadores para a tabela `usuario` -- ALTER TABLE `usuario` ADD CONSTRAINT `fk_usuario_funcionario1` FOREIGN KEY (`fk_funcionario`) REFERENCES `funcionario` (`pk_funcionario`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Limitadores para a tabela `venda` -- ALTER TABLE `venda` ADD CONSTRAINT `fk_venda_table11` FOREIGN KEY (`fk_usuario`) REFERENCES `usuario` (`pk_usuario`) ON DELETE NO ACTION ON UPDATE NO ACTION; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
c31800fc572098d3b6686dc0178e70f4e6b05ab5
SQL
TySag/Few_Projects_In_HUST
/Car/Sql code/select.sql
UTF-8
1,078
3.75
4
[]
no_license
use car; SELECT * FROM car.staffs; SELECT * FROM car.users; select * from cars; select * from carsinfo; select * from Orders; select (cars.Deposit - records.Cost) as returncost from records, cars where cars.cid = records.cid and records.date = (select max(date) from records); select * from records; select * from fixlist; select * from accident; select * from cars where price>=100 and price <=150; select fixlist.* from fixlist, records; select (cars.Deposit - records.Cost) as returncost from records, cars where cars.cid = records.cid group by date having records.date = max(records.date); select * from carsinfo; select * from staffs where sid = 'admin'; select * from users where uid = 'zsf'; select fixlist.Fid, records.Rid, records.Cid, records.Uid, Cars.Name,fixlist.fix, fixlist.cost from fixlist, records, Cars where fixlist.Rid = records.Rid and records.Cid = Cars.Cid; select Accident.Aid, records.Rid, records.Cid, records.Uid, Cars.Name, Accident.acc from Accident, records, Cars where Accident.Rid = records.Rid and records.Cid = Cars.Cid;
true
1f27cc9d48758f2dca67b27a51487d8ee7e6c01a
SQL
d88w/sql_projects
/004_prod_zr_waterfall.sql
UTF-8
7,409
3.328125
3
[]
no_license
------------------------------------------------------------ ------------------------------------------------------------ ------------- Zoom Room Waterfall Table -------------------- ------------------------------------------------------------ ------------------------------------------------------------ delete from rpt.zr_waterfall --------DATE LIMIT----- where load_date >= (CURRENT_DATE -30) ; INSERT INTO rpt.zr_waterfall WITH TA AS ( WITH T1 AS ( SELECT load_date, acc_number, acc_name, pd_name, SUM(rpc_quantity_entry) AS quantity_entry, SUM(rpc_quantity_change) AS quantity_change, SUM(rpc_quantity) AS quantity_exit, SUM(mrr_entry) AS mrr_entry, SUM(mrr_new) AS mrr_new, SUM(mrr_upsell) AS mrr_upsell, SUM(mrr_downsell) AS mrr_downsell, SUM(mrr_cancel) AS mrr_cancel, SUM(mrr_change) AS mrr_change, SUM(mrr_exit) AS mrr_exit FROM etl_acct_health.mrr_2_rpc_waterfall_apd WHERE pd_name = 'Zoom Rooms' AND rpc_quantity_change < 100000 --------DATE LIMIT----- and load_date >= (CURRENT_DATE -30) GROUP BY load_date, acc_number, acc_name, pd_name), T2 AS (SELECT mrs_date, account_number, fiscal_quarter, yearmonth, zoom_account_no, account_owner, salesdivision, billtocountry, billtostate, --------------ADDED employee_count employee_count, sales_group_exit, accountcreateddate, CASE WHEN (sales_group_exit= 'Int') AND (employee_count= 'Personal') THEN 'SB' WHEN (sales_group_exit= 'Int') AND (employee_count= '1-50') THEN 'SB' WHEN (sales_group_exit= 'Int') AND (employee_count= 'Just Me') THEN 'SB' WHEN (sales_group_exit= 'Int') AND (employee_count= '11-50') THEN 'SB' WHEN (sales_group_exit= 'Int') AND (employee_count= '2-10') THEN 'SB' WHEN (sales_group_exit= 'Int') AND (employee_count= 'Nov-50') THEN 'SB' WHEN (sales_group_exit= 'Int') AND (employee_count= '251-1000') THEN 'MM' WHEN (sales_group_exit= 'Int') AND (employee_count= '251-500') THEN 'MM' WHEN (sales_group_exit= 'Int') AND (employee_count= '51-250') THEN 'MM' WHEN (sales_group_exit= 'Int') AND (employee_count= 'Select One') THEN 'Majors' WHEN (sales_group_exit= 'Int') AND (employee_count= '2501+') THEN 'Majors' WHEN (sales_group_exit= 'Int') AND (employee_count= '1001-2500') THEN 'Commercial' WHEN (sales_group_exit= 'Int') AND (employee_count= '') THEN 'Majors' WHEN (sales_group_exit= 'Int') AND (employee_count IS NULL) THEN 'Majors' WHEN (sales_group_exit= 'Int') AND (employee_count= '5001-10000') THEN 'Majors' WHEN (sales_group_exit= 'Int') AND (employee_count= '10001+') THEN 'INTL' WHEN (sales_group_exit= 'Int') AND (employee_count= '501-1000') THEN 'Commercial' WHEN (sales_group_exit= 'Int') AND (employee_count= '1001-5000') THEN 'Majors' ELSE sales_group_exit END AS sales_group_exit_no_int, through_reseller, --- (true/false) is_reseller, ---(Yes/No) parent_account_name, parent_account_number, ultimate_parent_account_name, ultimate_parent_account_number, COUNT(zoom_account_no) FROM dm_sales.mrs_by_ad_growth_single --------DATE LIMIT----- where mrs_date >= (CURRENT_DATE -30) GROUP BY mrs_date, account_number, fiscal_quarter, yearmonth, zoom_account_no, zoom_account_no, account_owner, salesdivision, billtocountry, billtostate, --------------ADDED employee_count employee_count, through_reseller, --- (true/false) is_reseller, ---(Yes/No) parent_account_name, parent_account_number, ultimate_parent_account_name, ultimate_parent_account_number, sales_group_exit, sales_group_exit_no_int, accountcreateddate) SELECT T1.load_date, to_char(T1.load_date, 'yyyymm') AS yearmonth, to_char(DATEADD(month, -1, T1.load_date), 'yyyyq') AS fiscal_quarter, T2.zoom_account_no, T1.acc_number, T1.acc_name, T2.account_owner, T2.salesdivision, T2.billtocountry, T2.billtostate, --------------ADDED employee_count T2.employee_count, T2.accountcreateddate, T2.sales_group_exit, T2.sales_group_exit_no_int, CASE WHEN T2.through_reseller = 'true' THEN 'indirect' WHEN T2.is_reseller = 'Yes' THEN 'indirect' ELSE 'direct' END AS channel, T2.parent_account_name, T2.parent_account_number, T2.ultimate_parent_account_name, T2.ultimate_parent_account_number, T1.pd_name, T1.quantity_entry, T1.quantity_change, T1.quantity_exit, T1.mrr_entry, T1.mrr_new, T1.mrr_upsell, T1.mrr_downsell, T1.mrr_cancel, T1.mrr_change, T1.mrr_exit FROM T1 LEFT OUTER JOIN T2 ON T1.load_date = DATEADD(day, -1, T2.mrs_date) AND T1.acc_number = T2.account_number ), TB AS (SELECT b.accountnumber, a.zoom_account_number__c, 0 AS zoom_account_no, a.name AS account_name, a.industry, a.billingcountry, a.billingstate, --------------ADDED employee_count a.employee_count__c AS employee_count, CASE WHEN a.ispartner = 'true' THEN 'indirect' WHEN a.channel_account_owner__c IS NOT NULL THEN 'indirect' WHEN a.channel_account_owner__c <> '' THEN 'indirect' WHEN b.isreseller__c = 'Yes' THEN 'indirect' ELSE 'direct' END AS channel, a.segment__c, a.ls_company_industry__c, a.ls_company_sub_industry__c FROM src_sfdc.account a, src_zuora.account b WHERE a.zoom_account_number__c = CAST(b.zoom_account_number__c AS VARCHAR) AND a.type <> 'Free Trial') SELECT TA.load_date, to_char(load_date, 'yyyymm') AS yearmonth, to_char(DATEADD(month, -1, load_date), 'yyyyq') AS fiscal_quarter, CASE WHEN TA.zoom_account_no IS NULL THEN CAST(TRUNC(TB.zoom_account_no, 1) AS VARCHAR) ELSE TA.zoom_account_no END AS zoom_account_no, --TA.zoom_account_no, TA.acc_number, CASE WHEN TA.acc_name IS NULL THEN TB.account_name ELSE TA.acc_name END, TA.account_owner, TA.salesdivision, TB.ls_company_industry__c AS ls_industry, TB.ls_company_sub_industry__c AS ls_sub_industry, CASE WHEN TA.billtocountry IS NULL THEN TB.billingcountry ELSE TA.billtocountry END, CASE WHEN TA.billtostate IS NULL THEN TB.billingstate ELSE TA.billtostate END, CASE WHEN TA.sales_group_exit IS NULL THEN TB.segment__c WHEN TA.sales_group_exit = 'Channel' THEN TB.segment__c WHEN TA.sales_group_exit = '14.99' AND TA.quantity_change <> 0 THEN TB.segment__c ELSE TA.sales_group_exit END, CASE WHEN TA.sales_group_exit_no_int IS NULL THEN TB.segment__c WHEN TA.sales_group_exit_no_int = 'Channel' THEN TB.segment__c WHEN TA.sales_group_exit_no_int = '14.99' THEN TB.segment__c WHEN TA.sales_group_exit_no_int = 'Int' AND TB.segment__c = 'Int' THEN 'MM' WHEN TA.sales_group_exit_no_int = 'Intl' AND TB.segment__c = 'Intl' THEN 'MM' WHEN TA.sales_group_exit_no_int = 'INTL' AND TB.segment__c = 'INTL' THEN 'MM' WHEN TA.sales_group_exit_no_int = 'Int' THEN TB.segment__c WHEN TA.sales_group_exit_no_int = 'Intl' THEN TB.segment__c WHEN TA.sales_group_exit_no_int = 'INTL' THEN TB.segment__c ELSE TA.sales_group_exit_no_int END, CASE WHEN TA.channel IS NULL THEN TB.channel ELSE TA.channel END, TA.parent_account_name, TA.parent_account_number, TA.ultimate_parent_account_name, TA.ultimate_parent_account_number, TA.pd_name, TA.quantity_entry, TA.quantity_change, TA.quantity_exit, TA.mrr_entry, TA.mrr_new, TA.mrr_upsell, TA.mrr_downsell, TA.mrr_cancel, TA.mrr_change, TA.mrr_exit, --------------ADDED employee_count CASE WHEN TA.employee_count IS NULL THEN TB.employee_count ELSE TA.employee_count END, TA.accountcreateddate::DATE FROM TA LEFT OUTER JOIN TB ON TB.accountnumber = TA.acc_number; grant select on all tables in schema rpt to zm_domo_rpt_read_only; commit
true
4e6222e0a48f03955104d4b86e0b6a631cedf05a
SQL
MarcoFidelVasquezRivera/sql-random-insert-generator
/data/DDL.sql
UTF-8
1,049
3.734375
4
[]
no_license
CREATE TABLE Department ( deptNo CHAR(4) PRIMARY KEY, deptName VARCHAR(30) ); CREATE TABLE Employee ( empNo CHAR(4) PRIMARY KEY, fName VARCHAR(20), iName VARCHAR(20), address VARCHAR(30), DOB DATE, sex CHAR(1), positionn VARCHAR(30), deptNo CHAR(4), FOREIGN KEY (deptNo) REFERENCES Department, CHECK (sex IN ('M', 'F')) ); CREATE TABLE Projectt ( projNo CHAR(4) PRIMARY KEY, projName VARCHAR(20), deptNo CHAR(4), FOREIGN KEY (deptNo) REFERENCES Department ); CREATE TABLE WorksOn ( empNo CHAR(4), projNo CHAR(4), dateWorked DATE, hoursWorked INTEGER, FOREIGN KEY (empNo) REFERENCES Employee, FOREIGN KEY (projNo) REFERENCES Projectt, CONSTRAINT PK_D PRIMARY KEY (empNo, projNo, dateWorked) ); ALTER TABLE Department ADD mrgEmpNo CHAR(4) DEFAULT NULL; ALTER TABLE Department ADD FOREIGN KEY (mrgEmpNo) REFERENCES Employee (empNo);
true
387f4c574bca9d358c1bf1a6765918930651498e
SQL
patsjo/sportclub
/mysql/patches/sportclub_patch_1.1.sql
UTF-8
1,687
3.546875
4
[]
no_license
ALTER TABLE activity ADD INDEX IDX_ACTIVITY_ACTIVITYTYPE (activity_type_id), ADD CONSTRAINT FK_ACTIVITY_ACTIVITYTYPE FOREIGN KEY (activity_type_id) REFERENCES activity_type(activity_type_id); ALTER TABLE files ADD INDEX IDX_FILES_FOLDER (folder_id), ADD CONSTRAINT FK_FILES_FOLDER FOREIGN KEY (folder_id) REFERENCES folders(folder_id); ALTER TABLE news ADD INDEX IDX_NEWS_NEWSTYPE (news_type_id), ADD CONSTRAINT FK_NEWS_NEWSTYPE FOREIGN KEY (news_type_id) REFERENCES news_type(news_type_id); ALTER TABLE users ADD CONSTRAINT FK_USERS_COUNCIL FOREIGN KEY (council_id) REFERENCES councils(council_id); DELETE FROM user_groups WHERE user_id not in (select user_id from users); DELETE FROM user_groups WHERE group_id not in (select group_id from groups); ALTER TABLE user_groups ADD CONSTRAINT FK_USERGROUPS_USER FOREIGN KEY (user_id) REFERENCES users(user_id), ADD CONSTRAINT FK_USERGROUPS_GROUP FOREIGN KEY (group_id) REFERENCES groups(group_id); ALTER TABLE user_login ADD CONSTRAINT FK_USERLOGIN_USER FOREIGN KEY (user_id) REFERENCES users(user_id); UPDATE RACE_EVENT_RESULTS SET SPEED_RANKING = null, TECHNICAL_RANKING = null WHERE (SPEED_RANKING is not null OR TECHNICAL_RANKING is not null) AND (DIFFICULTY NOT IN ('Svart', 'Blå', 'Lila') OR EVENT_ID IN (SELECT EVENT_ID FROM RACE_EVENT WHERE SPORT_CODE != 'OL' OR RACE_DISTANCE = 'Sprint')); UPDATE RACE_EVENT_RESULTS_TEAM SET SPEED_RANKING = null, TECHNICAL_RANKING = null WHERE (SPEED_RANKING is not null OR TECHNICAL_RANKING is not null) AND (DIFFICULTY NOT IN ('Svart', 'Blå', 'Lila') OR EVENT_ID IN (SELECT EVENT_ID FROM RACE_EVENT WHERE SPORT_CODE != 'OL' OR RACE_DISTANCE = 'Sprint'));
true
2c8e8fbd4859a9168bc2b31b9d8a739043fc632d
SQL
htmlacademy-nodejs/1343543-buy-and-sell-3
/fill-db.sql
UTF-8
4,798
3.171875
3
[]
no_license
INSERT INTO users(email, password_hash, first_name, last_name, avatar) VALUES ('ivanov@example.com', '5f4dcc3b5aa765d61d8327deb882cf99', 'Иван', 'Иванов', 'avatar1.jpg'), ('petrov@example.com', '5f4dcc3b5aa765d61d8327deb882cf99', 'Пётр', 'Петров', 'avatar2.jpg'); INSERT INTO categories(name) VALUES ('Книги'), ('Разное'), ('Посуда'), ('Игры'), ('Животные'), ('Журналы'); ALTER TABLE offers DISABLE TRIGGER ALL; INSERT INTO offers(title, description, type, sum, picture, user_id) VALUES ('Куплю детские санки.', 'Таких предложений больше нет! Пользовались бережно и только по большим праздникам. Даю недельную гарантию. Продаю с болью в сердце...', 'SALE', 55459, 'item06.jpg', 2), ('Продам новую приставку Sony Playstation 5', 'При покупке с меня бесплатная доставка в черте города. Если товар не понравится — верну всё до последней копейки. Бонусом отдам все аксессуары. Таких предложений больше нет!', 'OFFER', 91134, 'item10.jpg', 2), ('Продам советскую посуду. Почти не разбита.', 'Пользовались бережно и только по большим праздникам. Даю недельную гарантию. При покупке с меня бесплатная доставка в черте города. Если найдёте дешевле — сброшу цену.', 'OFFER', 9509, 'item08.jpg', 2), ('Продам книги Стивена Кинга', 'Продаю с болью в сердце... Если найдёте дешевле — сброшу цену. Если товар не понравится — верну всё до последней копейки. При покупке с меня бесплатная доставка в черте города.', 'OFFER', 9571, 'item12.jpg', 1), ('Куплю детские санки.', 'Пользовались бережно и только по большим праздникам. Бонусом отдам все аксессуары. Таких предложений больше нет! Это настоящая находка для коллекционера!', 'SALE', 27647, 'item15.jpg', 2); ALTER TABLE offers ENABLE TRIGGER ALL; ALTER TABLE offer_categories DISABLE TRIGGER ALL; INSERT INTO offer_categories(offer_id, category_id) VALUES (1, 6), (2, 5), (3, 6), (4, 6), (5, 6); ALTER TABLE offer_categories ENABLE TRIGGER ALL; ALTER TABLE comments DISABLE TRIGGER ALL; INSERT INTO COMMENTS(text, user_id, offer_id) VALUES ('Неплохо, но дорого. С чем связана продажа? Почему так дешёво?', 2, 1), ('А сколько игр в комплекте? Продаю в связи с переездом. Отрываю от сердца. Совсем немного...', 2, 1), ('А где блок питания? Почему в таком ужасном состоянии? Неплохо, но дорого.', 1, 1), ('Почему в таком ужасном состоянии?', 2, 1), ('Совсем немного...', 2, 2), ('Вы что?! В магазине дешевле. А сколько игр в комплекте?', 2, 2), ('А сколько игр в комплекте? Неплохо, но дорого. Почему в таком ужасном состоянии?', 1, 2), ('А где блок питания? Совсем немного...', 1, 2), ('Совсем немного... Продаю в связи с переездом. Отрываю от сердца. Оплата наличными или перевод на карту?', 2, 3), ('Вы что?! В магазине дешевле. Почему в таком ужасном состоянии? Продаю в связи с переездом. Отрываю от сердца.', 1, 3), ('Неплохо, но дорого. А где блок питания? Оплата наличными или перевод на карту?', 2, 3), ('Продаю в связи с переездом. Отрываю от сердца. Оплата наличными или перевод на карту? Вы что?! В магазине дешевле.', 1, 3), ('Почему в таком ужасном состоянии?', 2, 4), ('Оплата наличными или перевод на карту?', 1, 4), ('Вы что?! В магазине дешевле. Оплата наличными или перевод на карту?', 2, 4), ('Почему в таком ужасном состоянии?', 2, 5); ALTER TABLE comments ENABLE TRIGGER ALL;
true
ec9fbbc06f8a693103779727800c22c0f357e192
SQL
gistol/etpz
/website/var/system/db-change-log_1516696412-5a66f35c07fe3.sql
UTF-8
4,642
3.609375
4
[]
no_license
UPDATE `classes` SET `id` = 3, `name` = 'Collection' WHERE (id = 3); /*--NEXT--*/ CREATE TABLE IF NOT EXISTS `object_query_3` ( `oo_id` int(11) NOT NULL default '0', `oo_classId` int(11) default '3', `oo_className` varchar(255) default 'Collection', PRIMARY KEY (`oo_id`) ) DEFAULT CHARSET=utf8mb4; /*--NEXT--*/ ALTER TABLE `object_query_3` ALTER COLUMN `oo_className` SET DEFAULT 'Collection'; /*--NEXT--*/ CREATE TABLE IF NOT EXISTS `object_store_3` ( `oo_id` int(11) NOT NULL default '0', PRIMARY KEY (`oo_id`) ) DEFAULT CHARSET=utf8mb4; /*--NEXT--*/ CREATE TABLE IF NOT EXISTS `object_relations_3` ( `src_id` int(11) NOT NULL DEFAULT '0', `dest_id` int(11) NOT NULL DEFAULT '0', `type` varchar(50) NOT NULL DEFAULT '', `fieldname` varchar(70) NOT NULL DEFAULT '0', `index` int(11) unsigned NOT NULL DEFAULT '0', `ownertype` enum('object','fieldcollection','localizedfield','objectbrick') NOT NULL DEFAULT 'object', `ownername` varchar(70) NOT NULL DEFAULT '', `position` varchar(70) NOT NULL DEFAULT '0', PRIMARY KEY (`src_id`,`dest_id`,`ownertype`,`ownername`,`fieldname`,`type`,`position`), KEY `index` (`index`), KEY `src_id` (`src_id`), KEY `dest_id` (`dest_id`), KEY `fieldname` (`fieldname`), KEY `position` (`position`), KEY `ownertype` (`ownertype`), KEY `type` (`type`), KEY `ownername` (`ownername`) ) DEFAULT CHARSET=utf8mb4; /*--NEXT--*/ ALTER TABLE `object_query_3` ADD INDEX `p_index_name` (`name`); /*--NEXT--*/ ALTER TABLE `object_store_3` ADD INDEX `p_index_name` (`name`); /*--NEXT--*/ ALTER TABLE `object_query_3` ADD COLUMN `val` varchar(190) NULL; /*--NEXT--*/ ALTER TABLE `object_store_3` ADD COLUMN `val` varchar(190) NULL; /*--NEXT--*/ ALTER TABLE `object_query_3` DROP INDEX `p_index_val`; /*--NEXT--*/ ALTER TABLE `object_store_3` DROP INDEX `p_index_val`; /*--NEXT--*/ ALTER TABLE `object_query_3` DROP INDEX `p_index_related_cat_attributes_to_collection`; /*--NEXT--*/ ALTER TABLE `object_store_3` DROP INDEX `p_index_related_cat_attributes_to_collection`; /*--NEXT--*/ ALTER TABLE `object_query_3` DROP INDEX `p_index_related_attributes_to_collection`; /*--NEXT--*/ ALTER TABLE `object_store_3` DROP INDEX `p_index_related_attributes_to_collection`; /*--NEXT--*/ CREATE OR REPLACE VIEW `object_3` AS SELECT * FROM `object_query_3` JOIN `objects` ON `objects`.`o_id` = `object_query_3`.`oo_id`; /*--NEXT--*/ CREATE TABLE IF NOT EXISTS `object_metadata_3` ( `o_id` int(11) NOT NULL default '0', `dest_id` int(11) NOT NULL default '0', `type` VARCHAR(50) NOT NULL DEFAULT '', `fieldname` varchar(71) NOT NULL, `column` varchar(190) NOT NULL, `data` text, `ownertype` ENUM('object','fieldcollection','localizedfield','objectbrick') NOT NULL DEFAULT 'object', `ownername` VARCHAR(70) NOT NULL DEFAULT '', `position` VARCHAR(70) NOT NULL DEFAULT '0', PRIMARY KEY (`o_id`, `dest_id`, `type`, `fieldname`, `column`, `ownertype`, `ownername`, `position`), INDEX `o_id` (`o_id`), INDEX `dest_id` (`dest_id`), INDEX `fieldname` (`fieldname`), INDEX `column` (`column`), INDEX `ownertype` (`ownertype`), INDEX `ownername` (`ownername`), INDEX `position` (`position`) ) DEFAULT CHARSET=utf8mb4; /*--NEXT--*/ CREATE TABLE IF NOT EXISTS `object_metadata_3` ( `o_id` int(11) NOT NULL default '0', `dest_id` int(11) NOT NULL default '0', `type` VARCHAR(50) NOT NULL DEFAULT '', `fieldname` varchar(71) NOT NULL, `column` varchar(190) NOT NULL, `data` text, `ownertype` ENUM('object','fieldcollection','localizedfield','objectbrick') NOT NULL DEFAULT 'object', `ownername` VARCHAR(70) NOT NULL DEFAULT '', `position` VARCHAR(70) NOT NULL DEFAULT '0', PRIMARY KEY (`o_id`, `dest_id`, `type`, `fieldname`, `column`, `ownertype`, `ownername`, `position`), INDEX `o_id` (`o_id`), INDEX `dest_id` (`dest_id`), INDEX `fieldname` (`fieldname`), INDEX `column` (`column`), INDEX `ownertype` (`ownertype`), INDEX `ownername` (`ownername`), INDEX `position` (`position`) ) DEFAULT CHARSET=utf8mb4; /*--NEXT--*/
true
55961c18208aab955b643071c33040cb812e33f6
SQL
doquockhanh/C0220H1-DoQuocKhanh
/Module2/CaseStudy/Furama Database/DB.sql
UTF-8
24,577
3.265625
3
[]
no_license
CREATE DATABASE furama_resort; USE furama_resort; -- -------------------------------------------------------------------------- -- NHAN VIEN CREATE TABLE vi_tri( IDvi_tri int PRIMARY KEY AUTO_INCREMENT, Ten_vi_tri VARCHAR(45) ); CREATE TABLE trinh_do( IDtrinh_do INT PRIMARY KEY AUTO_INCREMENT, trinh_do VARCHAR(45) ); CREATE TABLE bo_phan( IDbo_phan int PRIMARY KEY AUTO_INCREMENT, ten_bo_phan VARCHAR(45) ); CREATE TABLE nhan_vien( IDnhan_vien int PRIMARY KEY AUTO_INCREMENT, ho_ten VARCHAR(45), ngay_sinh DATE, so_cmnd VARCHAR(10), luong VARCHAR(45), so_dien_thoai VARCHAR(45), email VARCHAR(45), dia_chi VARCHAR(45), IDtrinh_do INT, FOREIGN KEY (IDtrinh_do) REFERENCES trinh_do (IDtrinh_do), IDbo_phan INT, FOREIGN KEY (IDbo_phan) REFERENCES bo_phan (IDbo_phan), IDvi_tri int, FOREIGN KEY (IDvi_tri) REFERENCES vi_tri (IDvi_tri) ); -- ------------------------------------------------------------------------- -- KHACH HANG CREATE TABLE loai_khach( IDloai_khach INT PRIMARY KEY AUTO_INCREMENT, ten_loai_khach VARCHAR(45) ); CREATE TABLE khach_hang( IDkhach_hang INT PRIMARY KEY AUTO_INCREMENT, IDloai_khach INT, FOREIGN KEY (IDloai_khach) REFERENCES loai_khach (IDloai_khach), ho_ten VARCHAR(45), ngay_sinh DATE, so_cmnd VARCHAR(45), so_dien_thoai VARCHAR(45), email VARCHAR(45), dia_chi VARCHAR(45) ); -- ------------------------------------------------------------------------ -- DICH VU CREATE TABLE loai_dich_vu( IDloai_dich_vu int PRIMARY KEY AUTO_INCREMENT, ten_loai_dich_vu VARCHAR(45) ); CREATE TABLE kieu_thue( IDkieu_thue int PRIMARY KEY AUTO_INCREMENT, ten_kieu_thue VARCHAR(45), gia INT ); CREATE TABLE dich_vu( IDdich_vu INT PRIMARY KEY AUTO_INCREMENT, ten_dich_vu VARCHAR(45), so_tang int, so_nguoi_toi_da VARCHAR(45), chi_phi_thue VARCHAR(45), IDkieu_thue INT, FOREIGN KEY (IDkieu_thue) REFERENCES kieu_thue (IDkieu_thue), IDloai_dich_vu INT, FOREIGN KEY (IDloai_dich_vu) REFERENCES loai_dich_vu (IDloai_dich_vu), trang_thai VARCHAR(45) ); CREATE TABLE dich_vu_di_kem( IDdich_vu_di_kem int PRIMARY KEY AUTO_INCREMENT, ten_dich_vu_di_kem VARCHAR(45), gia INT, don_vi INT, trang_thai_kha_dung VARCHAR(45) ); -- ------------------------------------------------------------------ -- HOP DONG CREATE TABLE hop_dong( IDhop_dong INT PRIMARY KEY AUTO_INCREMENT, IDnhan_vien INT, FOREIGN KEY (IDnhan_vien) REFERENCES nhan_vien (IDnhan_vien), IDkhach_hang INT, FOREIGN KEY (IDkhach_hang) REFERENCES khach_hang (IDkhach_hang), IDdich_vu INT, FOREIGN KEY (IDdich_vu) REFERENCES dich_vu (IDdich_vu), ngay_lam_hop_dong DATE, ngay_ket_thuc DATE, tien_dat_coc INT, tong_tien INT ); CREATE TABLE hop_dong_chi_tiet( IDhop_dong_chi_tiet INT PRIMARY KEY AUTO_INCREMENT, IDhop_dong INT , FOREIGN KEY (IDhop_dong) REFERENCES hop_dong (IDhop_dong), IDdich_vu_di_kem INT, FOREIGN KEY (IDdich_vu_di_kem) REFERENCES dich_vu_di_kem (IDdich_vu_di_kem), so_luong INT ); -- ---------------------------------------------------- -- YÊU CẦU 1 : THEM THONG TIN CHO TAT CA CAC BANG -- THEM THONG TIN BANG BO PHAN INSERT INTO `furama_resort`.`bo_phan` (`IDbo_phan`, `ten_bo_phan`) VALUES ('1', 'FM-CSKH'); INSERT INTO `furama_resort`.`bo_phan` (`IDbo_phan`, `ten_bo_phan`) VALUES ('2', 'FM-QLCS'); -- THEM THONG TIN BANG TRINH DO INSERT INTO `furama_resort`.`trinh_do` (`IDtrinh_do`, `trinh_do`) VALUES ('1', 'dai hoc'); INSERT INTO `furama_resort`.`trinh_do` (`IDtrinh_do`, `trinh_do`) VALUES ('2', 'cao dang'); INSERT INTO `furama_resort`.`trinh_do` (`IDtrinh_do`, `trinh_do`) VALUES ('3', 'trung cap'); -- THEM THONG TIN BANG VI TRI INSERT INTO `furama_resort`.`vi_tri` (`IDvi_tri`, `Ten_vi_tri`) VALUES ('1', 'quan li'); INSERT INTO `furama_resort`.`vi_tri` (`IDvi_tri`, `Ten_vi_tri`) VALUES ('2', 'nhan vien'); -- THEM THONG TIN BANG NHAN VIEN INSERT INTO `furama_resort`.`nhan_vien` (`ho_ten`, `ngay_sinh`, `so_cmnd`, `luong`, `so_dien_thoai`, `email`, `dia_chi`, `IDtrinh_do`, `IDbo_phan`, `IDvi_tri`) VALUES ('Đỗ Quốc Khánh', '2001-09-02', '12345678', '10000000', '123581321', 'khanhquocdo.qt', 'da nang', '1', '1', '1'); INSERT INTO `furama_resort`.`nhan_vien` (`ho_ten`, `ngay_sinh`, `so_cmnd`, `luong`, `so_dien_thoai`, `email`, `dia_chi`, `IDtrinh_do`, `IDbo_phan`, `IDvi_tri`) VALUES ('Đỗ Quốc Huy', '1999-09-16', '87654321', '10000000', '133555567', 'huy16905', 'quang tri', '1', '1', '2'); INSERT INTO `furama_resort`.`nhan_vien` (`ho_ten`, `ngay_sinh`, `so_cmnd`, `luong`, `so_dien_thoai`, `email`, `dia_chi`, `IDtrinh_do`, `IDbo_phan`, `IDvi_tri`) VALUES ('Nguyễn Ngọc Luân', '1969-01-01', '43125678', '20000000', '244466666', 'luan1169', 'quang nam', '2', '2', '1'); INSERT INTO `furama_resort`.`nhan_vien` (`ho_ten`, `ngay_sinh`, `so_cmnd`, `luong`, `so_dien_thoai`, `email`, `dia_chi`, `IDtrinh_do`, `IDbo_phan`, `IDvi_tri`) VALUES ('Nguyễn Hoàng Đại Nghĩa', '1999-09-06', '56748231', '15000000', '472874351', 'nghia6999', 'da nang', '3', '2', '2'); INSERT INTO `furama_resort`.`nhan_vien` (`ho_ten`, `ngay_sinh`, `so_cmnd`, `luong`, `so_dien_thoai`, `email`, `dia_chi`, `IDtrinh_do`, `IDbo_phan`, `IDvi_tri`) VALUES ('Trần Quang Đức', '1990-09-06', '56724781', '15000000', '276498162', 'duc0609', 'da nang', '3', '2', '2'); -- THEM THONG TIN LOAI KHACH HANG INSERT INTO `furama_resort`.`loai_khach` (`IDloai_khach`, `ten_loai_khach`) VALUES ('1', 'SLIVER'); INSERT INTO `furama_resort`.`loai_khach` (`IDloai_khach`, `ten_loai_khach`) VALUES ('2', 'GOLD'); INSERT INTO `furama_resort`.`loai_khach` (`IDloai_khach`, `ten_loai_khach`) VALUES ('3', 'PLASTINUM'); INSERT INTO `furama_resort`.`loai_khach` (`IDloai_khach`, `ten_loai_khach`) VALUES ('4', 'DIAMOND'); -- THEM THONG TIN KHACH HANG INSERT INTO `furama_resort`.`khach_hang` (`IDkhach_hang`, `IDloai_khach`, `ho_ten`, `ngay_sinh`, `so_cmnd`, `so_dien_thoai`, `email`, `dia_chi`) VALUES ('1', '4', 'Lê Hữu Ái', '1990-03-05', '22447733', '12563653472', 'aile05031990', 'Quảng Ngãi'); INSERT INTO `furama_resort`.`khach_hang` (`IDkhach_hang`, `IDloai_khach`, `ho_ten`, `ngay_sinh`, `so_cmnd`, `so_dien_thoai`, `email`, `dia_chi`) VALUES ('2', '3', 'Lê Việt Nhật ', '1969-08-12', '57483942', '75647387459', 'vietnhat1208', 'Quảng Trị'); INSERT INTO `furama_resort`.`khach_hang` (`IDkhach_hang`, `IDloai_khach`, `ho_ten`, `ngay_sinh`, `so_cmnd`, `so_dien_thoai`, `email`, `dia_chi`) VALUES ('3', '2', 'Đỗ Quốc Khánh', '2001-09-02', '45634587', '39252343472', 'khanhquocdo.qt', 'Đà Nẵng'); INSERT INTO `furama_resort`.`khach_hang` (`IDkhach_hang`, `IDloai_khach`, `ho_ten`, `ngay_sinh`, `so_cmnd`, `so_dien_thoai`, `email`, `dia_chi`) VALUES ('4', '4', 'Đại Nghĩa', '1994-07-30', '47293624', '23746254673', 'dainghia3007', 'Vinh'); INSERT INTO `furama_resort`.`khach_hang` (`IDkhach_hang`, `IDloai_khach`, `ho_ten`, `ngay_sinh`, `so_cmnd`, `so_dien_thoai`, `email`, `dia_chi`) VALUES ('5', '1', 'Nguyễn Văn Tân', '2003-07-01', '48535724', '2973682073', 'vantan0107', 'Hà Nội'); INSERT INTO `furama_resort`.`khach_hang` (`IDkhach_hang`, `IDloai_khach`, `ho_ten`, `ngay_sinh`, `so_cmnd`, `so_dien_thoai`, `email`, `dia_chi`) VALUES ('6', '1', 'Nguyễn Văn Tân', '2003-07-01', '48535724', '2973682073', 'vantan0107', 'Hà Nội'); -- THEM THONG TIN DICH VU DI KEM INSERT INTO `furama_resort`.`dich_vu_di_kem` (`IDdich_vu_di_kem`, `ten_dich_vu_di_kem`, `gia`, `don_vi`, `trang_thai_kha_dung`) VALUES ('1', 'Massage', '1000000', '1', 'available'); INSERT INTO `furama_resort`.`dich_vu_di_kem` (`IDdich_vu_di_kem`, `ten_dich_vu_di_kem`, `gia`, `don_vi`, `trang_thai_kha_dung`) VALUES ('2', 'Karaoke', '700000', '1', 'available'); INSERT INTO `furama_resort`.`dich_vu_di_kem` (`IDdich_vu_di_kem`, `ten_dich_vu_di_kem`, `gia`, `don_vi`, `trang_thai_kha_dung`) VALUES ('3', 'Thức ăn', '200000', '1', 'available'); INSERT INTO `furama_resort`.`dich_vu_di_kem` (`IDdich_vu_di_kem`, `ten_dich_vu_di_kem`, `gia`, `don_vi`, `trang_thai_kha_dung`) VALUES ('4', 'Nước uống', '100000', '1', 'available'); INSERT INTO `furama_resort`.`dich_vu_di_kem` (`IDdich_vu_di_kem`, `ten_dich_vu_di_kem`, `gia`, `don_vi`, `trang_thai_kha_dung`) VALUES ('5', 'Tham quan Resort', '200000', '1', 'available'); -- THEM THONG TIN KIEU THUE INSERT INTO `furama_resort`.`kieu_thue` (`IDkieu_thue`, `ten_kieu_thue`, `gia`) VALUES ('1', 'Kieu1 ', '1000000 '); INSERT INTO `furama_resort`.`kieu_thue` (`IDkieu_thue`, `ten_kieu_thue`, `gia`) VALUES ('2', 'Kieu2', '5000000'); INSERT INTO `furama_resort`.`kieu_thue` (`IDkieu_thue`, `ten_kieu_thue`, `gia`) VALUES ('3', 'Kieu3', '10000000'); -- THEM THONG TIN LOAI DICH VU INSERT INTO `furama_resort`.`loai_dich_vu` (`IDloai_dich_vu`, `ten_loai_dich_vu`) VALUES ('1', 'Villa'); INSERT INTO `furama_resort`.`loai_dich_vu` (`IDloai_dich_vu`, `ten_loai_dich_vu`) VALUES ('2', 'House'); INSERT INTO `furama_resort`.`loai_dich_vu` (`IDloai_dich_vu`, `ten_loai_dich_vu`) VALUES ('3', 'Room'); -- THEM THONG TIN DICH VU INSERT INTO `furama_resort`.`dich_vu` (`IDdich_vu`, `ten_dich_vu`, `so_tang`, `so_nguoi_toi_da`, `chi_phi_thue`, `IDkieu_thue`, `IDloai_dich_vu`, `trang_thai`) VALUES ('1', 'VL-001', '5', '10', '10000000', '1', '1', 'available'); INSERT INTO `furama_resort`.`dich_vu` (`IDdich_vu`, `ten_dich_vu`, `so_tang`, `so_nguoi_toi_da`, `chi_phi_thue`, `IDkieu_thue`, `IDloai_dich_vu`, `trang_thai`) VALUES ('2', 'VL-002', '2', '6', '6000000', '2', '1', 'available'); INSERT INTO `furama_resort`.`dich_vu` (`IDdich_vu`, `ten_dich_vu`, `so_tang`, `so_nguoi_toi_da`, `chi_phi_thue`, `IDkieu_thue`, `IDloai_dich_vu`, `trang_thai`) VALUES ('3', 'HO-001', '1', '4', '1000000', '3', '2', 'available'); INSERT INTO `furama_resort`.`dich_vu` (`IDdich_vu`, `ten_dich_vu`, `so_tang`, `so_nguoi_toi_da`, `chi_phi_thue`, `IDkieu_thue`, `IDloai_dich_vu`, `trang_thai`) VALUES ('4', 'HO-002', '3', '10', '2000000', '3', '2', 'available'); INSERT INTO `furama_resort`.`dich_vu` (`IDdich_vu`, `ten_dich_vu`, `so_tang`, `so_nguoi_toi_da`, `chi_phi_thue`, `IDkieu_thue`, `IDloai_dich_vu`, `trang_thai`) VALUES ('5', 'RO-001', '1', '2', '500000', '3', '3', 'available'); INSERT INTO `furama_resort`.`dich_vu` (`IDdich_vu`, `ten_dich_vu`, `so_tang`, `so_nguoi_toi_da`, `chi_phi_thue`, `IDkieu_thue`, `IDloai_dich_vu`, `trang_thai`) VALUES ('6', 'RO-002', '1', '4', '700000', '3', '3', 'available'); -- THEM THONG TIN HOP DONG INSERT INTO `furama_resort`.`hop_dong` (`IDhop_dong`, `IDnhan_vien`, `IDkhach_hang`, `IDdich_vu`, `ngay_lam_hop_dong`, `ngay_ket_thuc`, `tien_dat_coc`, `tong_tien`) VALUES ('1', '2', '5', '6', '2020-05-15', '2020-05-20', '500000', '5000000'); INSERT INTO `furama_resort`.`hop_dong` (`IDhop_dong`, `IDnhan_vien`, `IDkhach_hang`, `IDdich_vu`, `ngay_lam_hop_dong`, `ngay_ket_thuc`, `tien_dat_coc`, `tong_tien`) VALUES ('2', '1', '1', '1', '2020-05-10', '2020-05-13', '5000000', '33000000'); INSERT INTO `furama_resort`.`hop_dong` (`IDhop_dong`, `IDnhan_vien`, `IDkhach_hang`, `IDdich_vu`, `ngay_lam_hop_dong`, `ngay_ket_thuc`, `tien_dat_coc`, `tong_tien`) VALUES ('3', '3', '2', '5', '2020-05-05', '2020-05-13', '500000', '5900000'); INSERT INTO `furama_resort`.`hop_dong` (`IDhop_dong`, `IDnhan_vien`, `IDkhach_hang`, `IDdich_vu`, `ngay_lam_hop_dong`, `ngay_ket_thuc`, `tien_dat_coc`, `tong_tien`) VALUES ('4', '4', '4', '4', '2020-04-10', '2020-04-13', '1000000', '8000000'); INSERT INTO `furama_resort`.`hop_dong` (`IDhop_dong`, `IDnhan_vien`, `IDkhach_hang`, `IDdich_vu`, `ngay_lam_hop_dong`, `ngay_ket_thuc`, `tien_dat_coc`, `tong_tien`) VALUES ('5', '1', '1', '1', '2020-01-15', '2020-01-20', '10000000', '51000000'); INSERT INTO `furama_resort`.`hop_dong` (`IDhop_dong`, `IDnhan_vien`, `IDkhach_hang`, `IDdich_vu`, `ngay_lam_hop_dong`, `ngay_ket_thuc`, `tien_dat_coc`, `tong_tien`) VALUES ('6', '1', '1', '1', '2020-05-10', '2020-05-13', '5000000', '33000000'); -- THEM THONG TIN HOP DONG CHI TIET INSERT INTO `furama_resort`.`hop_dong_chi_tiet` (`IDhop_dong_chi_tiet`, `IDhop_dong`, `IDdich_vu_di_kem`, `so_luong`) VALUES ('1', '1', '1', '1'); INSERT INTO `furama_resort`.`hop_dong_chi_tiet` (`IDhop_dong_chi_tiet`, `IDhop_dong`, `IDdich_vu_di_kem`, `so_luong`) VALUES ('2', '2', '1', '1'); INSERT INTO `furama_resort`.`hop_dong_chi_tiet` (`IDhop_dong_chi_tiet`, `IDhop_dong`, `IDdich_vu_di_kem`, `so_luong`) VALUES ('3', '3', '2', '2'); INSERT INTO `furama_resort`.`hop_dong_chi_tiet` (`IDhop_dong_chi_tiet`, `IDhop_dong`, `IDdich_vu_di_kem`, `so_luong`) VALUES ('4', '4', '3', '5'); INSERT INTO `furama_resort`.`hop_dong_chi_tiet` (`IDhop_dong_chi_tiet`, `IDhop_dong`, `IDdich_vu_di_kem`, `so_luong`) VALUES ('5', '5', '1', '1'); INSERT INTO `furama_resort`.`hop_dong_chi_tiet` (`IDhop_dong_chi_tiet`, `IDhop_dong`, `IDdich_vu_di_kem`, `so_luong`) VALUES ('6', '1', '2', '1'); -- SUA 1 SO THONG TIN UPDATE `furama_resort`.`dich_vu` SET `IDkieu_thue` = '1' WHERE (`IDdich_vu` = '6'); UPDATE `furama_resort`.`dich_vu` SET `IDkieu_thue` = '3' WHERE (`IDdich_vu` = '2'); UPDATE `furama_resort`.`dich_vu` SET `IDkieu_thue` = '2' WHERE (`IDdich_vu` = '4'); UPDATE `furama_resort`.`dich_vu` SET `IDkieu_thue` = '1' WHERE (`IDdich_vu` = '5'); UPDATE `furama_resort`.`dich_vu` SET `IDkieu_thue` = '2' WHERE (`IDdich_vu` = '3'); UPDATE `furama_resort`.`dich_vu` SET `IDkieu_thue` = '3' WHERE (`IDdich_vu` = '1'); UPDATE `furama_resort`.`kieu_thue` SET `gia` = '1000000' WHERE (`IDkieu_thue` = '2'); UPDATE `furama_resort`.`kieu_thue` SET `gia` = '2000000' WHERE (`IDkieu_thue` = '3'); UPDATE `furama_resort`.`kieu_thue` SET `gia` = '500000' WHERE (`IDkieu_thue` = '1'); -- ---------------------------------------------------------------------------------- -- YÊU CẦU 2 : SELECT* FROM furama_resort.nhan_vien WHERE char_length(nhan_vien.ho_ten) < 15 AND (nhan_vien.ho_ten LIKE 'H%' OR nhan_vien.ho_ten LIKE 'K%' OR nhan_vien.ho_ten LIKE 'T%'); -- ---------------------------------------------------------------------------------- -- YÊU CẦU 3 : hiển thị khách hàng 18 - 50 tuổi đến từ Đà Nẵng và Quảng trị SELECT* FROM furama_resort.khach_hang WHERE khach_hang.dia_chi = 'Đà Nẵng' OR khach_hang.dia_chi = 'Quảng Trị' AND year(now()) - year(khach_hang.ngay_sinh) > 17 AND year(now()) - year(khach_hang.ngay_sinh) < 51; -- xac dinh tuoi khac hang theo ngay -- SELECT* FROM furama_resort.khach_hang -- WHERE to_days(now()) - to_days(khach_hang.ngay_sinh) > 18*365 AND to_days(now()) - to_days(khach_hang.ngay_sinh) < 50*365 -- --------------------------------------------------------------------------------- -- YÊU CẦU 4: hiển thị số lần đặt phòng của khách hàng diamond SELECT ho_ten 'Họ Tên', count(ho_ten) 'Số lần đặt phòng' FROM furama_resort.hop_dong JOIN furama_resort.khach_hang ON hop_dong.IDkhach_hang = khach_hang.IDkhach_hang AND khach_hang.IDloai_khach = 4 GROUP BY(ho_ten) ORDER BY count(ho_ten); -- --------------------------------------------------------------------------------- -- YÊU CẦU 5: hiển thị thông tin hợp đồng của khách hàng SELECT khach_hang.IDkhach_hang, khach_hang.ho_ten, loai_khach.ten_loai_khach , IDhop_dong, ten_dich_vu, ngay_lam_hop_dong, ngay_ket_thuc, tong_tien FROM khach_hang LEFT JOIN hop_dong ON khach_hang.IDkhach_hang = hop_dong.IDkhach_hang LEFT JOIN loai_khach ON khach_hang.IDloai_khach = loai_khach.IDloai_khach LEFT JOIN dich_vu ON hop_dong.IDdich_vu = dich_vu.IDdich_vu; -- ----------------------------------------------------------------------------------------- -- YÊU CẦU 6: SELECT DISTINCT dich_vu.IDdich_vu , dich_vu.ten_dich_vu, dich_vu.chi_phi_thue, dich_vu.ten_dich_vu FROM dich_vu INNER JOIN (SELECT hop_dong.IDdich_vu ID FROM hop_dong WHERE hop_dong.ngay_lam_hop_dong > '2020-05-10' Or hop_dong.ngay_lam_hop_dong < '2020-01-01') TB ON TB.ID = dich_vu.IDdich_vu; -- 6 2020-05-15 -- 1 2020-05-10 -- 5 2020-05-05 -- 4 2020-04-10 -- 1 2020-01-15 -- 1 2020-05-10 -- 6. Hiển thị IDDichVu, TenDichVu, DienTich, ChiPhiThue, TenLoaiDichVu của tất cả các -- loại Dịch vụ chưa từng được Khách hàng thực hiện đặt từ quý 1 của năm 2019 (Quý 1 là tháng 1, 2, 3). -- ---------------------------------------------------------------------------------------- -- YÊU CẦU 7: hiển thị thông tin của dịch vụ được đặt từ t1 -> t4 nhưng chưa được đặt trong t5 năm 2020 SELECT hop_dong.IDdich_vu, dich_vu.ten_dich_vu, dich_vu.so_nguoi_toi_da, dich_vu.chi_phi_thue, loai_dich_vu.ten_loai_dich_vu FROM hop_dong INNER JOIN dich_vu ON hop_dong.IDdich_vu = dich_vu.IDdich_vu INNER JOIN loai_dich_vu ON dich_vu.IDloai_dich_vu = loai_dich_vu.IDloai_dich_vu WHERE (month(hop_dong.ngay_lam_hop_dong) >= 01 AND month(hop_dong.ngay_lam_hop_dong) >= 04) AND year(hop_dong.ngay_lam_hop_dong) = 2020 AND hop_dong.IDdich_vu NOT IN ( SELECT hop_dong.IDdich_vu FROM hop_dong WHERE month(hop_dong.ngay_lam_hop_dong) = 05 AND year(hop_dong.ngay_lam_hop_dong) = 2020 ); -- 7. Hiển thị thông tin IDDichVu, TenDichVu, DienTich, SoNguoiToiDa, ChiPhiThue, -- TenLoaiDichVu của tất cả các loại dịch vụ đã từng được Khách hàng đặt phòng trong -- năm 2018 nhưng chưa từng được Khách hàng đặt phòng trong năm 2019. -- ----------------------------------------------------------------------------------------- -- YÊU CẦU 8: SELECT DISTINCT ho_ten FROM khach_hang; SELECT khach_hang.ho_ten FROM khach_hang GROUP BY (khach_hang.ho_ten); SELECT DISTINCTROW ho_ten FROM khach_hang; -- ---------------------------------------------------------------------------- -- YÊU CẦU 9: số khách đặt phòng theo tháng SELECT month(hop_dong.ngay_lam_hop_dong) 'Tháng', count(hop_dong.IDhop_dong) 'Số khách đặt phòng' FROM furama_resort.hop_dong WHERE year(hop_dong.ngay_lam_hop_dong) = '2020' GROUP BY month(hop_dong.ngay_lam_hop_dong); -- ------------------------------------------------------------------------------------- -- YÊU CẦU 10: số dịch vụ đi kèm mỗi hợp đồng SELECT hop_dong.IDhop_dong 'Mã hợp đồng', count(hop_dong_chi_tiet.IDhop_dong) 'Số lượng dịch vụ đi kèm' FROM hop_dong INNER JOIN hop_dong_chi_tiet ON hop_dong.IDhop_dong = hop_dong_chi_tiet.IDhop_dong GROUP BY hop_dong.IDhop_dong; -- -------------------------------------------------------------------------------------- -- YÊU CẦU 11: thông tin dịch vụ đi kèm đã được sử dụng SELECT* FROM dich_vu_di_kem WHERE IDdich_vu_di_kem IN ( SELECT DISTINCT hop_dong_chi_tiet.IDdich_vu_di_kem FROM hop_dong_chi_tiet WHERE hop_dong_chi_tiet.IDhop_dong IN ( SELECT hop_dong.IDhop_dong FROM hop_dong WHERE hop_dong.IDkhach_hang IN ( SELECT khach_hang.IDkhach_hang FROM khach_hang INNER JOIN loai_khach ON khach_hang.IDloai_khach = loai_khach.IDloai_khach WHERE loai_khach.IDloai_khach = 4 AND khach_hang.dia_chi = 'Vinh' OR khach_hang.dia_chi = 'Quảng Ngãi' ) ) ) ; -- -------------------------------------------------------------------------------------- -- YÊU CẦU 12: SELECT DISTINCT hop_dong.IDdich_vu, nhan_vien.ho_ten 'Tên nhân viên', khach_hang.ho_ten 'Tên khách hàng', khach_hang.so_dien_thoai, dich_vu.ten_dich_vu, count(hop_dong_chi_tiet.IDhop_dong) 'Số lượng DVDK', hop_dong.tien_dat_coc FROM hop_dong INNER JOIN nhan_vien ON hop_dong.IDnhan_vien = nhan_vien.IDnhan_vien INNER JOIN khach_hang ON hop_dong.IDkhach_hang = khach_hang.IDkhach_hang INNER JOIN dich_vu ON hop_dong.IDdich_vu = dich_vu.IDdich_vu INNER JOIN hop_dong_chi_tiet ON hop_dong.IDhop_dong = hop_dong_chi_tiet.IDhop_dong WHERE month(hop_dong.ngay_lam_hop_dong) >= 05 AND year(hop_dong.ngay_lam_hop_dong) = 2020 AND hop_dong.IDdich_vu not in ( SELECT DISTINCT hop_dong.IDdich_vu FROM hop_dong WHERE month(hop_dong.ngay_lam_hop_dong) BETWEEN 01 and 04 AND year(hop_dong.ngay_lam_hop_dong) = 2020 ) GROUP BY hop_dong_chi_tiet.IDhop_dong; -- chọn ra dịch vụ được sử dụng trong tháng 5 nhưng không được sử dụng trước đó từ tháng 1 đến 4 -- 6 2020-05-15 -- 1 2020-05-10 -- 5 2020-05-05 -- 4 2020-04-10 -- 1 2020-01-15 -- 1 2020-05-10 -- -------------------------------------------------------------------------------------- -- YÊU CẦU 13 : Hiển thị thông tin các Dịch vụ đi kèm được sử dụng nhiều nhất bởi các Khách hàng đã đặt phòng SELECT * FROM dich_vu_di_kem JOIN ( SELECT hop_dong_chi_tiet.IDdich_vu_di_kem 'ID', count(hop_dong_chi_tiet.IDdich_vu_di_kem) 'solandung' FROM hop_dong_chi_tiet GROUP BY hop_dong_chi_tiet.IDdich_vu_di_kem ) tb ON dich_vu_di_kem.IDdich_vu_di_kem = tb.ID HAVING solandung = max(solandung); -- --------------------------------------------------------------------------------------- -- YÊU CẦU 14 : Hiển thị thông tin tất cả các Dịch vụ đi kèm chỉ mới được sử dụng một lần duy nhất. SELECT* FROM dich_vu_di_kem WHERE dich_vu_di_kem.IDdich_vu_di_kem IN( SELECT IDdich_vu_di_kem FROM hop_dong_chi_tiet GROUP BY hop_dong_chi_tiet.IDdich_vu_di_kem HAVING count(hop_dong_chi_tiet.IDdich_vu_di_kem) = 1 ); -- --------------------------------------------------------------------------------------------- -- YÊU CẦU 15 : Hiển thi thông tin của tất cả nhân viên mới chỉ lập được tối đa 3 hợp đồng trong năm 2020 SELECT nhan_vien.IDnhan_vien, nhan_vien.ho_ten, trinh_do.trinh_do, bo_phan.ten_bo_phan, nhan_vien.so_dien_thoai, nhan_vien.dia_chi FROM nhan_vien INNER JOIN bo_phan ON nhan_vien.IDbo_phan = bo_phan.IDbo_phan INNER JOIN trinh_do ON nhan_vien.IDtrinh_do = trinh_do.IDtrinh_do WHERE nhan_vien.IDnhan_vien IN ( SELECT hop_dong.IDnhan_vien FROM hop_dong WHERE year(hop_dong.ngay_lam_hop_dong) = 2020 GROUP BY hop_dong.IDnhan_vien HAVING count(hop_dong.IDnhan_vien) BETWEEN 1 and 3 ); -- ------------------------------------------------------------------------------------ -- YÊU CẦU 16 : chưa xử lí được ALTER TABLE furama_resort.hop_dong DROP FOREIGN KEY `hop_dong_ibfk_1` ; ALTER TABLE furama_resort.nhan_vien DROP FOREIGN KEY `nhan_vien_ibfk_1` ; ALTER TABLE furama_resort.nhan_vien DROP FOREIGN KEY `nhan_vien_ibfk_2` ; ALTER TABLE furama_resort.nhan_vien DROP FOREIGN KEY `nhan_vien_ibfk_3` ; DELETE FROM furama_resort.nhan_vien WHERE nhan_vien.IDnhan_vien NOT IN ( SELECT DISTINCT nhan_vien.IDnhan_vien FROM hop_dong INNER JOIN nhan_vien ON hop_dong.IDnhan_vien = nhan_vien.IDnhan_vien ); -- 16. Xóa những Nhân viên chưa từng lập được hợp đồng nào từ năm 2017 đến năm 2019. -- ------------------------------------------------------------------------------------ -- YÊU CẦU 17 : UPDATE furama_resort.khach_hang JOIN ( SELECT hop_dong.IDkhach_hang 'ID' FROM hop_dong INNER JOIN khach_hang ON hop_dong.IDkhach_hang = khach_hang.IDkhach_hang WHERE khach_hang.IDloai_khach = 3 AND hop_dong.tong_tien > 5000000 AND year(hop_dong.ngay_lam_hop_dong) = 2020 ) AS TB ON khach_hang.IDkhach_hang = TB.ID SET IDloai_khach = 4 WHERE TB.ID = 2; -- 17. Cập nhật thông tin những khách hàng có TenLoaiKhachHang từ -- Platinium lên Diamond, chỉ cập nhật những khách hàng đã từng đặt -- phòng với tổng Tiền thanh toán trong năm 2019 là lớn hơn 10.000.000 VNĐ. -- ----------------------------------------------------------------------------------- -- YÊU CẦU 18 : delete khachhang,hopdong,hopdongchitiet from khachhang inner join hopdong on khachhang.IdKhachHang = hopdong.IdKhachHang inner join hopdongchitiet on hopdong.IdHopDong = hopdongchitiet.IdHopDong where not exists (select hopdong.IdHopDong where year(hopdong.ngayLamHopDong) > '2016' and khachhang.IdKhachHang = hopdong.IdKhachHang); -- xóa khách hàng có hợp đồng trước 2016 -- ----------------------------------------------------------------------------------- -- YÊU CẦU 19 : tăng giá dịch vụ đi kèm sử dụng trong năm 2020 trên 3 lần lên gấp đôi UPDATE dich_vu_di_kem JOIN (SELECT IDdich_vu_di_kem 'IDDVDK' , count(IDdich_vu_di_kem) 'solanSD' FROM hop_dong_chi_tiet INNER JOIN hop_dong ON hop_dong.IDhop_dong = hop_dong_chi_tiet.IDhop_dong WHERE year(hop_dong.ngay_lam_hop_dong) = 2020 GROUP BY IDdich_vu_di_kem ) AS table_ID ON dich_vu_di_kem.IDdich_vu_di_kem = table_ID.IDDVDK SET dich_vu_di_kem.gia = (dich_vu_di_kem.gia*2) WHERE solanSD >= 3; -- ------------------------------------------------------------------------------------ -- YÊU CẦU 20 : SELECT nhan_vien.IDnhan_vien, nhan_vien.ho_ten, nhan_vien.email, nhan_vien.so_dien_thoai, nhan_vien.ngay_sinh, nhan_vien.dia_chi FROM nhan_vien; SELECT khach_hang.IDkhach_hang, khach_hang.ho_ten, khach_hang.email, khach_hang.so_dien_thoai, khach_hang.ngay_sinh, khach_hang.dia_chi FROM khach_hang; -- END -----
true
4eda3d244b9998a253ec03676a1c540e3ae35246
SQL
kiransnath/sql_scripts
/Redshift_json_parsing.sql
UTF-8
8,559
3.203125
3
[]
no_license
drop table if exists prod_b.seq_0_to_10; CREATE TABLE prod_b.seq_0_to_10 AS ( SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 ); drop table if exists prod_b.tmp_pi_aggregated; create table prod_b.tmp_pi_aggregated as ( WITH exploded_array AS ( SELECT payment_authentication_id , payment_session_id , prior_authentication_id , payment_instrument_id , payment_authentication_data_reference_id , bin , payment_sub_method , bin_issuing_country , authentication_amount , authentication_currency_code , authentication_acquirer_mid , authentication_acquirer_country , enforce_authentication , bypass_authentication_failures , authentication_category , risk_transaction_id , risk_transaction_data_sent , risk_transaction_data_status_code , three_ds_terminal_state , three_ds_requester_challenge_indicator , three_ds_requester_challenge_indicator_description , acs_challenge_mandated , authentication_type , authentication_type_description , transaction_status , transaction_status_description , challenge_cancel_reason , challenge_cancel_description , three_ds_provider , three_ds_provider_mid , init_reference_id , acs_transaction_id , directory_server_transaction_id , three_ds_server_transaction_id , three_ds_version , enrollment_response , device_channel , requester_initiated_type , requester_initiated_description , transaction_category , allow_further_payment_processing , reason_code , reason_description , authentication_created_dt , challenge_requested_dt , init_requested_dt , authentication_completed_dt , payment_intents , provider_operations , etl_file_name , etl_version , etl_inserted_dt , JSON_EXTRACT_ARRAY_ELEMENT_TEXT(payment_intents,seq.i) AS payment_intents_aggregated FROM pdm.prod_b.fact_tds_authentication, prod_b.seq_0_to_10 AS seq WHERE payment_intents is not null AND seq.i < JSON_ARRAY_LENGTH(payment_intents) ) SELECT payment_authentication_id , payment_session_id , prior_authentication_id , payment_instrument_id , payment_authentication_data_reference_id , bin , payment_sub_method , bin_issuing_country , authentication_amount , authentication_currency_code , authentication_acquirer_mid , authentication_acquirer_country , enforce_authentication , bypass_authentication_failures , authentication_category , risk_transaction_id , risk_transaction_data_sent , risk_transaction_data_status_code , three_ds_terminal_state , three_ds_requester_challenge_indicator , three_ds_requester_challenge_indicator_description , acs_challenge_mandated , authentication_type , authentication_type_description , transaction_status , transaction_status_description , challenge_cancel_reason , challenge_cancel_description , three_ds_provider , three_ds_provider_mid , init_reference_id , acs_transaction_id , directory_server_transaction_id , three_ds_server_transaction_id , three_ds_version , enrollment_response , device_channel , requester_initiated_type , requester_initiated_description , transaction_category , allow_further_payment_processing , reason_code , reason_description , authentication_created_dt , challenge_requested_dt , init_requested_dt , authentication_completed_dt , payment_intents , provider_operations , etl_file_name , etl_version , etl_inserted_dt , json_extract_path_text(payment_intents_aggregated,'business_model') as business_model FROM exploded_array ) union ( SELECT payment_authentication_id , payment_session_id , prior_authentication_id , payment_instrument_id , payment_authentication_data_reference_id , bin , payment_sub_method , bin_issuing_country , authentication_amount , authentication_currency_code , authentication_acquirer_mid , authentication_acquirer_country , enforce_authentication , bypass_authentication_failures , authentication_category , risk_transaction_id , risk_transaction_data_sent , risk_transaction_data_status_code , three_ds_terminal_state , three_ds_requester_challenge_indicator , three_ds_requester_challenge_indicator_description , acs_challenge_mandated , authentication_type , authentication_type_description , transaction_status , transaction_status_description , challenge_cancel_reason , challenge_cancel_description , three_ds_provider , three_ds_provider_mid , init_reference_id , acs_transaction_id , directory_server_transaction_id , three_ds_server_transaction_id , three_ds_version , enrollment_response , device_channel , requester_initiated_type , requester_initiated_description , transaction_category , allow_further_payment_processing , reason_code , reason_description , authentication_created_dt , challenge_requested_dt , init_requested_dt , authentication_completed_dt , payment_intents , provider_operations , etl_file_name , etl_version , etl_inserted_dt , NULL FROM pdm.prod_b.fact_tds_authentication, prod_b.seq_0_to_10 AS seq WHERE payment_intents is null) ; DROP VIEW IF EXISTS prod_b.ods_fact_tds_authentication_busmodel_list; DROP VIEW IF EXISTS prod_b.ods_fact_tds_authentication_busmodel_list; drop table if exists prod_b.tmp_business_model_list; create table prod_b.tmp_business_model_list as SELECT distinct payment_authentication_id, payment_session_id, payment_instrument_id, payment_authentication_data_reference_id, bin, payment_sub_method, bin_issuing_country, authentication_amount, authentication_currency_code, authentication_acquirer_mid, authentication_acquirer_country, enforce_authentication, bypass_authentication_failures, authentication_category, risk_transaction_id, risk_transaction_data_sent, risk_transaction_data_status_code, three_ds_terminal_state, three_ds_requester_challenge_indicator, three_ds_requester_challenge_indicator_description, acs_challenge_mandated, authentication_type, authentication_type_description, transaction_status, transaction_status_description, challenge_cancel_reason, challenge_cancel_description, three_ds_provider, three_ds_provider_mid, init_reference_id, acs_transaction_id, directory_server_transaction_id, three_ds_server_transaction_id, three_ds_version, enrollment_response, device_channel, requester_initiated_type, requester_initiated_description, transaction_category, allow_further_payment_processing, reason_code, reason_description, authentication_created_dt, challenge_requested_dt, init_requested_dt, authentication_completed_dt, payment_intents, provider_operations, etl_file_name, etl_version, etl_inserted_dt, LISTAGG(business_model,', ') -- WITHIN GROUP (ORDER BY business_model) OVER (PARTITION BY payment_authentication_id) AS business_model_list FROM prod_b.tmp_pi_aggregated; CREATE VIEW prod_b.ods_fact_tds_authentication_busmodel_list AS select * from prod_b.tmp_business_model_list; Grant all on prod_b.ods_fact_tds_authentication_busmodel_list to group pdm_admin; Grant all on prod_b.ods_fact_tds_authentication_busmodel_list to group pdm_etl; Grant select on prod_b.ods_fact_tds_authentication_busmodel_list to group pdm_power_user; Grant select on prod_b.ods_fact_tds_authentication_busmodel_list to group pdm_user; Grant select on prod_b.ods_fact_tds_authentication_busmodel_list to group pdm_report;
true
b6e046462c20e00f414aa9df9098cd9c3d8d26b0
SQL
erickjhorman/Crub-Mysql-Node-js-
/Database.sql
UTF-8
902
3.40625
3
[]
no_license
Create database transito; use transito; Create table propietario ( id_cedulapro int(10) not null auto_increment, nombre varchar(15) not null, apellido varchar(15) not null, PRIMARY KEY (id_cedulapro) ); create table vehiculo( id_placa int(7) not null auto_increment, cedulapro_id int(3) not null, modelo varchar(10) not null, año int(5) not null, PRIMARY KEY (id_placa), FOREIGN key (cedulapro_id) REFERENCES propietario (id_cedulapro) ); create table multa ( id_multa int(3) not null auto_increment primary key, fecha_multa date not null, placa_id varchar(7) not null REFERENCES propietario(vehiculo), descripcion_multa varchar(30) not null, estado_multa TINYINT(1) not null, valor_multa int(8) not null, cedula int(10) not null ); show tables; describe vehiculo; ALTER TABLE vehiculo MODIFY cedulapro_id int(3) NOT NULL;
true
af124998b906d79e5038b859a36705a094dbcdb2
SQL
Procrat/eva
/migrations/2019-01-31-052443_create_time_segments/up.sql
UTF-8
736
3.6875
4
[ "Apache-2.0" ]
permissive
CREATE TABLE time_segments ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL, start INTEGER NOT NULL, period INTEGER NOT NULL ); CREATE TABLE time_segment_ranges ( segment_id INTEGER NOT NULL, start INTEGER NOT NULL, end INTEGER NOT NULL ); -- Add a default time segment: daily from 9 to 5 INSERT INTO time_segments VALUES ( 0, 'Default', strftime('%s', 'now', 'weekday 1', 'start of day', 'utc', '9 hours'), 24 * 60 * 60 ); INSERT INTO time_segment_ranges VALUES ( 0, strftime('%s', 'now', 'weekday 1', 'start of day', 'utc', '9 hours'), strftime('%s', 'now', 'weekday 1', 'start of day', 'utc', '17 hours') ); ALTER TABLE tasks ADD COLUMN time_segment_id INTEGER NOT NULL DEFAULT 0;
true
4c72e73c4be7985073edebef2b030dded8efc049
SQL
duncan0801/final-group-project-backend
/prisma/migrations/20210908162304_/migration.sql
UTF-8
277
2.8125
3
[]
no_license
/* Warnings: - A unique constraint covering the columns `[date,time]` on the table `Appointment` will be added. If there are existing duplicate values, this will fail. */ -- CreateIndex CREATE UNIQUE INDEX "Appointment.date_time_unique" ON "Appointment"("date", "time");
true
f436ac2d6a57b4477e4d7fd4f79963d5d6a1ed20
SQL
qq605905613/SSMDEMO
/MchntAuditAssign00/MchntAuditAssign00/sql/tbl_args_reason_conf.ddl.sql
UTF-8
722
3.21875
3
[]
no_license
SET CURRENT SCHEMA ARGS; CREATE TABLE ARGS.TBL_ARGS_REASON_CONF ( MCHNT_TP CHARACTER(4) WITH DEFAULT NOT NULL, SPEC_DISC_TP CHARACTER(2) WITH DEFAULT NOT NULL, SPEC_DISC_LVL CHARACTER(1) WITH DEFAULT NOT NULL, REASON_TP CHARACTER(4) WITH DEFAULT NOT NULL, REC_ST CHARACTER(1) WITH DEFAULT NOT NULL, COMMENTS VARCHAR(160) WITH DEFAULT NOT NULL, REC_CRT_TS TIMESTAMP DEFAULT CURRENT TIMESTAMP NOT NULL, REC_UPD_TS TIMESTAMP DEFAULT CURRENT TIMESTAMP NOT NULL, CONSTRAINT IND_MMGM_RT_PK PRIMARY KEY (REASON_TP,MCHNT_TP,SPEC_DISC_TP,SPEC_DISC_LVL) ); GRANT ALL ON ARGS.TBL_ARGS_REASON_CONF TO USER OP_MGMAP; GRANT SELECT ON ARGS.TBL_ARGS_REASON_CONF TO USER OP_MGMMN;
true
627684cd0fed94be07e9fc2ca7d7ecec596df492
SQL
dssg/rws_accident_prediction_public
/database/archive/create_panel.sql
UTF-8
1,209
3.84375
4
[ "MIT" ]
permissive
-- this joins ongeval to hectopunten through the ongeval_hectopunten link with panel_staging_0 as ( select o.datetime,date_trunc('hour', o.datetime) as datetime_rounded,h.weather_station, o.ongekey, h.hectoyearkey, 1 as acccident, h.num_lanes_max from rws_clean.ongevallen as o left join rws_clean.ong_hect_link as l on o.ongekey = l.ongekey left join rws_clean.hectopunten as h on l.hectoyearkey = h.hectoyearkey), -- panel_staging_1 connects panel with knmi_features based on weather station -- and rounded time panel_staging_1 as ( select panel_staging_0.*, kf.avg_wind_speed_hr -- add features from knmi_features here. from panel_staging_0 left join rws_clean.knmi_features as kf on panel_staging_0.datetime_rounded = kf.datetime and panel_staging_0.weather_station = kf.weather_station ), -- panel_staging_2 is for extracting temporal features. panel_staging_2 as ( select *, extract(hour from panel_staging_1.datetime)::int as hour, extract(month from panel_staging_1.datetime)::int as month, extract(isodow from panel_staging_1.datetime)::int as day_of_week --monday is 1 from panel_staging_1 ) -- If we wanted flow we would need panel_staging_3 so on and so forth. select * from panel_staging_2 ;
true
5b50e731e07a07bac188f66725d0a4210d8497dc
SQL
egor-rogov/postgres_air
/tables/booking_jsonb.sql
UTF-8
1,566
4.03125
4
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/* creates JSONB representation of simplified booking * type passenger_record should be created PRIOR to this script run * see types subdirectory */ CREATE TYPE booking_leg_record_2 AS (booking_leg_id integer, leg_num integer, booking_id integer, flight flight_record); --create simplified booking type CREATE TYPE booking_record_2 AS ( booking_id integer, booking_ref text, booking_name text, email text, account_id integer, booking_legs booking_leg_record_2[], passengers passenger_record[] ); CREATE TABLE booking_jsonb AS SELECT b.booking_id, to_jsonb ( row ( b.booking_id, b.booking_ref, b.booking_name, b.email, b.account_id, ls.legs, ps.passengers ) :: booking_record_2 ) as cplx_booking FROM booking b JOIN (SELECT booking_id, array_agg(row ( booking_leg_id, leg_num, booking_id, row(f.flight_id, flight_no, departure_airport, dep.airport_name, arrival_airport, arv.airport_name, scheduled_departure, scheduled_arrival )::flight_record )::booking_leg_record_2) legs FROM booking_leg l JOIN flight f ON f.flight_id = l.flight_id JOIN airport dep ON dep.airport_code = f.departure_airport JOIN airport arv ON arv.airport_code = f.arrival_airport GROUP BY booking_id) ls ON b.booking_id = ls.booking_id JOIN ( SELECT booking_id, array_agg( row(passenger_id, booking_id, passenger_no, last_name, first_name):: passenger_record) as passengers FROM passenger GROUP by booking_id) ps ON ls.booking_id = ps.booking_id ) ; CREATE INDEX idxgin ON booking_jsonb USING gin (cplx_booking);
true
c4e8ce060e3d1886528999d75a503fbf4a8cf27c
SQL
reuxm/Fil_Rouge
/scripts/garagepoefrUpdated.sql
UTF-8
21,607
2.9375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.2 -- https://www.phpmyadmin.net/ -- -- Hôte : 127.0.0.1 -- Généré le : jeu. 23 jan. 2020 à 14:57 -- Version du serveur : 10.4.10-MariaDB -- Version de PHP : 7.1.33 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `garagepoefr` -- CREATE DATABASE IF NOT EXISTS `garagepoefr` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `garagepoefr`; -- -------------------------------------------------------- -- -- Structure de la table `client` -- CREATE TABLE `client` ( `id` int(11) NOT NULL, `nom` varchar(50) NOT NULL, `prenom` varchar(50) NOT NULL, `adresse` varchar(50) NOT NULL, `code_postal` varchar(50) NOT NULL, `ville` varchar(50) NOT NULL, `telephone` varchar(50) NOT NULL, `mobile` varchar(50) NOT NULL, `cloturer` bit(1) NOT NULL DEFAULT b'0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `client` -- INSERT INTO `client` (`id`, `nom`, `prenom`, `adresse`, `code_postal`, `ville`, `telephone`, `mobile`, `cloturer`) VALUES (2, 'Glass', 'Imelda', '293-3436 Dui. Route', '20555', 'Flushing', '01 04 73 21 96', '06 23 83 80 58', b'0'), (3, 'Ross', 'Jescie', '4084 Vitae Ave', '69115', 'Coronel', '02 65 32 94 99', '06 05 16 64 78', b'0'), (4, 'Dalton', 'Kato', '434-5556 Dictum Ave', '47770', 'Kursk', '01 58 61 91 15', '06 54 65 81 47', b'0'), (5, 'Raymond', 'Kiona', '731-9200 Vitae Impasse', '44802', 'Pemberton', '09 16 82 50 09', '06 88 47 18 01', b'0'), (6, 'Lester', 'Oleg', 'Appartement 687-4416 Non, Rue', '88380', 'Cappelle sul Tavo', '02 39 86 08 46', '06 38 64 74 29', b'0'), (7, 'Hendrix', 'Seth', '336-8860 Id, Route', '72573', 'Moncton', '03 99 49 74 37', '06 17 77 53 38', b'0'), (8, 'Wooten', 'Uma', 'Appartement 355-9888 Fermentum Av.', '00253', 'Solihull', '07 61 15 20 48', '06 37 75 78 12', b'0'), (9, 'Dodson', 'Hedy', 'CP 387, 7069 Malesuada. Chemin', '66981', 'Arlon', '08 84 72 18 75', '06 67 50 26 71', b'0'), (10, 'Marsh', 'Freya', '613-920 Scelerisque Route', '77610', 'Gentinnes', '03 03 82 45 40', '06 74 54 42 50', b'0'), (11, 'Houston', 'Tad', 'CP 600, 9729 Ac Chemin', '28144', 'Aubervilliers', '07 58 19 68 67', '06 53 52 27 77', b'0'), (12, 'Fields', 'Tara', '318 Lorem Rue', '64911', 'Keswick', '02 10 64 60 89', '06 22 79 90 43', b'0'), (13, 'Arnold', 'Carla', 'Appartement 235-5506 Nullam Impasse', '49243', 'Gubkin', '07 92 17 12 27', '06 18 97 30 39', b'0'), (14, 'Hess', 'Jelani', 'CP 956, 9193 Adipiscing Chemin', '90141', 'Huntsville', '05 95 25 13 01', '06 42 76 03 83', b'0'), (15, 'Houston', 'Gary', '497-113 Fames Chemin', '71580', 'Vierzon', '09 71 69 22 39', '06 86 73 45 95', b'0'), (16, 'Dickson', 'Kiayada', '338-6910 Donec Ave', '48439', 'Steenhuffel', '06 62 23 87 37', '06 87 39 77 12', b'0'), (17, 'Livingston', 'Emery', '8956 Diam Rue', '98846', 'Bannu', '02 63 64 63 95', '06 86 28 54 65', b'0'), (18, 'Lopez', 'Libby', 'Appartement 102-4410 Parturient Rue', '54462', 'Cochin', '07 48 37 29 53', '06 62 44 08 63', b'0'), (19, 'Patrick', 'Hamilton', 'Appartement 749-1273 Magnis Rue', '12044', 'Christchurch', '08 64 82 87 47', '06 43 64 87 47', b'0'), (20, 'Pruitt', 'Warren', 'CP 525, 9403 Non, Rd.', '34952', 'Fogo', '03 19 30 83 33', '06 79 12 99 39', b'0'), (21, 'Mays', 'Simon', '1601 Porttitor Av.', '29739', 'March', '08 89 97 02 22', '06 40 71 27 09', b'0'), (22, 'Hardin', 'Ross', 'CP 716, 3394 Magna. Av.', '25483', 'Bellevue', '07 52 03 78 71', '06 94 68 38 99', b'0'), (23, 'Solomon', 'Zane', '662-8408 Nullam Impasse', '79399', 'Foz do Iguaçu', '01 87 84 32 28', '06 20 27 15 94', b'0'), (24, 'Rasmussen', 'Rowan', 'Appartement 601-1258 Nulla. Av.', '82398', 'Orciano Pisano', '04 89 27 11 40', '06 03 34 60 40', b'0'), (25, 'Cooke', 'Luke', '7643 Sapien Rue', '57924', 'Zuienkerke', '02 72 06 28 04', '06 67 92 39 70', b'0'), (26, 'Ray', 'Anjolie', '9530 Et Chemin', '44904', 'Nagpur', '07 52 92 50 96', '06 42 10 94 31', b'0'), (27, 'Odonnell', 'Idola', 'CP 290, 2585 Nam Impasse', '75230', 'Joondalup', '01 37 40 82 00', '06 42 37 51 40', b'0'), (28, 'Hanson', 'Kelsie', '120-1400 Senectus Chemin', '74569', 'Aiseau', '03 87 00 52 19', '06 16 12 54 05', b'0'), (29, 'Saunders', 'Shad', 'CP 160, 5988 Vulputate, Rue', '58832', 'Raurkela', '01 62 03 59 35', '06 00 01 38 80', b'0'), (30, 'Day', 'Quin', 'CP 918, 7652 Iaculis Impasse', '99160', 'Hasselt', '08 99 39 03 84', '06 46 84 25 82', b'0'), (31, 'Bonner', 'Austin', 'Appartement 470-7081 Cursus Route', '37630', 'Toronto', '03 24 84 89 81', '06 82 34 81 71', b'0'), (32, 'Bolton', 'Moses', 'CP 730, 1058 Ornare. Route', '52039', 'Melazzo', '06 69 86 87 86', '06 92 85 75 10', b'0'), (33, 'Bolton', 'Emma', 'CP 886, 6167 Porttitor Avenue', '01613', 'Grosseto', '06 34 96 36 15', '06 12 05 81 91', b'0'), (34, 'Pacheco', 'Nina', '658-7403 Varius Rd.', '97692', 'Gimhae', '01 01 28 80 94', '06 83 09 63 04', b'0'), (35, 'Preston', 'Wyoming', 'CP 338, 6870 Morbi Rue', '14921', 'Gresham', '03 18 38 14 11', '06 09 94 30 32', b'0'), (36, 'Acosta', 'Flynn', 'CP 136, 9315 Aenean Chemin', '66949', 'Bairnsdale', '06 14 56 03 94', '06 12 20 56 62', b'0'), (37, 'Mooney', 'Omar', 'CP 148, 1478 Dapibus Ave', '13663', 'Santarém', '08 08 96 02 10', '06 89 76 59 34', b'0'), (38, 'Weeks', 'Wylie', 'Appartement 813-831 Nec Impasse', '55493', 'Oxford County', '07 56 43 11 44', '06 67 71 93 97', b'0'), (39, 'Frederick', 'Haley', 'Appartement 681-8534 Metus. Rd.', '08587', 'Navadwip', '03 65 30 07 78', '06 28 17 56 46', b'0'), (40, 'Greene', 'Madeline', 'CP 882, 1020 Pede. Rue', '77835', 'Soissons', '06 64 44 00 95', '06 88 74 45 57', b'0'), (41, 'Obrien', 'George', 'CP 203, 604 Donec Chemin', '90680', 'Cranbrook', '06 45 43 44 25', '06 08 35 79 22', b'0'), (42, 'Stuart', 'Jesse', '3112 Lobortis. Route', '49396', 'Baardegem', '09 93 52 91 76', '06 79 67 81 32', b'0'), (43, 'Mills', 'Risa', 'Appartement 470-5528 Est Rue', '67846', 'Scena/Schenna', '02 66 91 66 61', '06 64 84 60 23', b'0'), (44, 'Todd', 'Patricia', 'Appartement 289-9443 Mauris. Ave', '56626', '100 Mile House', '09 57 42 54 81', '06 47 93 99 73', b'0'), (45, 'Castro', 'Hilda', '650-2873 Eleifend. Av.', '17581', 'Castelluccio Inferiore', '03 95 48 47 97', '06 98 64 59 10', b'0'), (46, 'Gray', 'Sawyer', '6216 Vel Route', '38034', 'Fontanigorda', '02 39 16 01 62', '06 46 69 62 90', b'0'), (47, 'Pope', 'Isaiah', 'Appartement 416-3033 Nonummy Avenue', '29800', 'Caen', '07 12 81 89 72', '06 66 37 38 01', b'0'), (48, 'Campbell', 'Keiko', 'CP 769, 2011 Tempor Route', '64558', 'King Township', '08 53 94 00 75', '06 93 77 71 97', b'0'), (49, 'Gillespie', 'Keefe', 'CP 426, 5719 Lectus Route', '68679', 'Río Bueno', '03 25 84 20 37', '06 21 72 88 95', b'0'), (50, 'Vaughn', 'Noel', 'Appartement 465-9283 Enim, Route', '64376', 'Canora', '03 07 01 08 54', '06 14 41 66 02', b'0'), (51, 'Barnes', 'Bruno', '5535 Auctor. Av.', '64665', 'Castellina in Chianti', '09 46 57 39 60', '06 76 41 81 79', b'0'); -- -------------------------------------------------------- -- -- Structure de la table `commande_piece` -- CREATE TABLE `commande_piece` ( `id` int(11) NOT NULL, `id_user` int(11) NOT NULL, `id_piece` int(11) NOT NULL, `quantite` int(11) NOT NULL, `date_creation` date NOT NULL, `date_cloture` date DEFAULT NULL, `etat` bit(1) NOT NULL DEFAULT b'0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `commande_piece` -- INSERT INTO `commande_piece` (`id`, `id_user`, `id_piece`, `quantite`, `date_creation`, `date_cloture`, `etat`) VALUES (1, 2, 3, 1, '2020-01-23', '2020-01-23', b'1'), (2, 1, 1, 2, '2020-01-23', NULL, b'0'), (3, 1, 10, 1, '2020-01-23', NULL, b'0'), (4, 2, 10, 1, '2020-01-23', NULL, b'0'); -- -------------------------------------------------------- -- -- Structure de la table `commande_vehicule` -- CREATE TABLE `commande_vehicule` ( `id` int(11) NOT NULL, `id_devis` int(11) DEFAULT NULL, `etat` bit(1) DEFAULT b'0', `date_creation` date DEFAULT NULL, `date_cloture` date DEFAULT NULL, `livre` bit(1) NOT NULL DEFAULT b'0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `commande_vehicule` -- INSERT INTO `commande_vehicule` (`id`, `id_devis`, `etat`, `date_creation`, `date_cloture`, `livre`) VALUES (1, 1, b'1', '2020-01-23', NULL, b'0'), (2, 1, b'0', '2020-01-23', NULL, b'0'); -- -------------------------------------------------------- -- -- Structure de la table `devis` -- CREATE TABLE `devis` ( `id` int(11) NOT NULL, `id_client` int(11) NOT NULL, `id_vehicule` int(11) NOT NULL, `id_user` int(11) NOT NULL, `date_creation` date NOT NULL, `etatdevis` bit(1) DEFAULT b'0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `devis` -- INSERT INTO `devis` (`id`, `id_client`, `id_vehicule`, `id_user`, `date_creation`, `etatdevis`) VALUES (1, 2, 3, 1, '2020-01-06', b'1'), (2, 3, 2, 2, '2020-01-21', b'0'), (3, 12, 9, 2, '2020-01-22', b'1'); -- -------------------------------------------------------- -- -- Structure de la table `facture_devis` -- CREATE TABLE `facture_devis` ( `id` int(11) NOT NULL, `id_devis` int(11) NOT NULL, `prixHT` float DEFAULT 0, `tauxTVA` float DEFAULT 0.2, `date_creation` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Structure de la table `facture_fiche` -- CREATE TABLE `facture_fiche` ( `id` int(11) NOT NULL, `id_fiche` int(11) NOT NULL, `prixHT` float DEFAULT 0, `tauxTVA` float DEFAULT 0.2, `date_creation` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Structure de la table `fiche` -- CREATE TABLE `fiche` ( `id` int(11) NOT NULL, `id_client` int(11) NOT NULL, `id_user` int(11) NOT NULL, `etatfiche` bit(1) DEFAULT b'0', `id_priorite` int(11) NOT NULL, `Date_creation` date NOT NULL, `Date_cloture` date DEFAULT NULL, `description` text DEFAULT NULL, `prixht` float NOT NULL DEFAULT 0, `tauxTVA` float NOT NULL DEFAULT 0.2 ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `fiche` -- INSERT INTO `fiche` (`id`, `id_client`, `id_user`, `etatfiche`, `id_priorite`, `Date_creation`, `Date_cloture`, `description`, `prixht`, `tauxTVA`) VALUES (1, 11, 1, b'0', 1, '2020-01-23', NULL, 'Voiture qui ne fonctionne plus', 1000, 0.2), (2, 6, 1, b'0', 4, '2020-01-23', NULL, 'Problème d\'essuie glace', 50, 0.2); -- -------------------------------------------------------- -- -- Structure de la table `pieces` -- CREATE TABLE `pieces` ( `id` int(11) NOT NULL, `libelle` varchar(50) NOT NULL, `quantite` int(11) DEFAULT NULL, `date_saisie` date DEFAULT NULL, `description` text DEFAULT NULL, `prixht` float NOT NULL DEFAULT 0, `tauxTVA` float NOT NULL DEFAULT 0.2 ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `pieces` -- INSERT INTO `pieces` (`id`, `libelle`, `quantite`, `date_saisie`, `description`, `prixht`, `tauxTVA`) VALUES (1, 'Moteur', 3, '2020-01-06', NULL, 0, 0.2), (2, 'Roue', 8, '2019-12-25', NULL, 0, 0.2), (3, 'Bougie', 50, '2019-11-12', NULL, 0, 0.2), (4, 'Volant', 4, '2019-11-05', NULL, 0, 0.2), (5, 'Vitre', 1, '2020-01-07', NULL, 0, 0.2), (6, 'Pare choc', 7, '2019-09-09', NULL, 0, 0.2), (7, 'Portière', 2, '2019-11-19', NULL, 0, 0.2), (8, 'Siège', 6, '2019-10-14', NULL, 0, 0.2), (9, 'Essuie Glace', 100, '2019-02-03', NULL, 0, 0.2), (10, 'Pare brise', 10, '2018-03-22', NULL, 0, 0.2), (11, 'Poignée', 60, '2017-12-22', NULL, 0, 0.2), (12, 'Poignée', 60, '2017-12-22', NULL, 0, 0.2); -- -------------------------------------------------------- -- -- Structure de la table `priorite` -- CREATE TABLE `priorite` ( `id` int(11) NOT NULL, `libelle` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `priorite` -- INSERT INTO `priorite` (`id`, `libelle`) VALUES (1, 'Très Urgent'), (2, 'Urgent'), (3, 'Normal'), (4, 'Non prioritaire'); -- -------------------------------------------------------- -- -- Structure de la table `profil` -- CREATE TABLE `profil` ( `id` int(11) NOT NULL, `name` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `profil` -- INSERT INTO `profil` (`id`, `name`) VALUES (1, 'MECANICIEN'), (2, 'ADMINISTRATEUR'), (3, 'COMMERCIAL'), (4, 'CHEF_ATELIER'), (5, 'MAGASINIER'); -- -------------------------------------------------------- -- -- Structure de la table `profil_user` -- CREATE TABLE `profil_user` ( `id_user` int(11) NOT NULL, `id_profil` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `profil_user` -- INSERT INTO `profil_user` (`id_user`, `id_profil`) VALUES (1, 2), (1, 4), (2, 3); -- -------------------------------------------------------- -- -- Structure de la table `tache` -- CREATE TABLE `tache` ( `id` int(11) NOT NULL, `commentaire` varchar(200) DEFAULT NULL, `id_user` int(11) NOT NULL, `id_fiche` int(11) NOT NULL, `id_priorite` int(11) NOT NULL, `id_piece` int(11) NOT NULL, `qte` int(11) DEFAULT 0, `etattache` bit(1) DEFAULT b'0', `libelle` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `tache` -- INSERT INTO `tache` (`id`, `commentaire`, `id_user`, `id_fiche`, `id_priorite`, `id_piece`, `qte`, `etattache`, `libelle`) VALUES (1, '', 1, 1, 3, 9, 2, b'0', 'Changement d\'essuie glace'), (2, '', 2, 2, 1, 1, 1, b'0', 'Changement moteur'); -- -------------------------------------------------------- -- -- Structure de la table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `lastname` varchar(50) NOT NULL, `firstname` varchar(50) NOT NULL, `login` varchar(15) NOT NULL, `pwd` varchar(100) NOT NULL, `suspended` bit(1) DEFAULT 0; ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `users` -- INSERT INTO `users` (`id`, `lastname`, `firstname`, `login`, `pwd`) VALUES (1, 'DURAND', 'JEAN', 'JDURAND', '$2a$10$CoalNJDmjR0xc3ZuCwXPp.NYCKeoahilrOgRROE0GVx2fQU/P4GpW'), (2, 'MARTIN', 'JEANNE', 'JMARTIN', '$2a$10$CoalNJDmjR0xc3ZuCwXPp.NYCKeoahilrOgRROE0GVx2fQU/P4GpW'); -- -------------------------------------------------------- -- -- Structure de la table `vehicule` -- CREATE TABLE `vehicule` ( `id` int(11) NOT NULL, `modele` varchar(50) NOT NULL, `quantite` int(11) NOT NULL, `prixHT` float DEFAULT 0, `date_creation` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `vehicule` -- INSERT INTO `vehicule` (`id`, `modele`, `quantite`, `prixHT`, `date_creation`) VALUES (1, '307', 12, 15345, '2019-12-12'), (2, 'GOLF IV', 6, 17450, '2019-12-11'), (3, 'Porsche 911', 2, 120000, '2019-10-05'), (4, 'Tesla Modèle 3', 1, 200000, '2017-10-08'), (5, 'Afla Romeo 166', 10, 30000, '2018-11-06'), (6, 'Audi A4', 2, 40000, '2019-08-05'), (7, 'Bugatti Type 35', 1, 1300000, '2020-01-22'), (8, 'Chevrolet Orlando', 5, 20000, '2018-11-25'), (9, 'Ford Puma', 6, 15000, '2018-01-11'), (10, 'Jaguar F-Type', 2, 70000, '2019-11-02'), (11, 'Maserati Granturismo', 1, 80000, '2018-08-15'); -- -- Index pour les tables déchargées -- -- -- Index pour la table `client` -- ALTER TABLE `client` ADD PRIMARY KEY (`id`); -- -- Index pour la table `commande_piece` -- ALTER TABLE `commande_piece` ADD PRIMARY KEY (`id`), ADD KEY `id_user` (`id_user`), ADD KEY `id_piece` (`id_piece`); -- -- Index pour la table `commande_vehicule` -- ALTER TABLE `commande_vehicule` ADD PRIMARY KEY (`id`), ADD KEY `id_devis` (`id_devis`); -- -- Index pour la table `devis` -- ALTER TABLE `devis` ADD PRIMARY KEY (`id`), ADD KEY `id_client` (`id_client`), ADD KEY `id_user` (`id_user`), ADD KEY `id_vehicule` (`id_vehicule`); -- -- Index pour la table `facture_devis` -- ALTER TABLE `facture_devis` ADD PRIMARY KEY (`id`), ADD KEY `id_devis` (`id_devis`); -- -- Index pour la table `facture_fiche` -- ALTER TABLE `facture_fiche` ADD PRIMARY KEY (`id`), ADD KEY `id_fiche` (`id_fiche`); -- -- Index pour la table `fiche` -- ALTER TABLE `fiche` ADD PRIMARY KEY (`id`), ADD KEY `id_client` (`id_client`), ADD KEY `id_user` (`id_user`), ADD KEY `id_priorite` (`id_priorite`); -- -- Index pour la table `pieces` -- ALTER TABLE `pieces` ADD PRIMARY KEY (`id`); -- -- Index pour la table `priorite` -- ALTER TABLE `priorite` ADD PRIMARY KEY (`id`); -- -- Index pour la table `profil` -- ALTER TABLE `profil` ADD PRIMARY KEY (`id`); -- -- Index pour la table `profil_user` -- ALTER TABLE `profil_user` ADD KEY `id_user` (`id_user`), ADD KEY `id_profil` (`id_profil`); -- -- Index pour la table `tache` -- ALTER TABLE `tache` ADD PRIMARY KEY (`id`), ADD KEY `id_user` (`id_user`), ADD KEY `id_fiche` (`id_fiche`), ADD KEY `id_priorite` (`id_priorite`), ADD KEY `id_piece` (`id_piece`); -- -- Index pour la table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- Index pour la table `vehicule` -- ALTER TABLE `vehicule` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT pour les tables déchargées -- -- -- AUTO_INCREMENT pour la table `client` -- ALTER TABLE `client` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=52; -- -- AUTO_INCREMENT pour la table `commande_piece` -- ALTER TABLE `commande_piece` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT pour la table `commande_vehicule` -- ALTER TABLE `commande_vehicule` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT pour la table `devis` -- ALTER TABLE `devis` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT pour la table `facture_devis` -- ALTER TABLE `facture_devis` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT pour la table `facture_fiche` -- ALTER TABLE `facture_fiche` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT pour la table `fiche` -- ALTER TABLE `fiche` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT pour la table `pieces` -- ALTER TABLE `pieces` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT pour la table `priorite` -- ALTER TABLE `priorite` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT pour la table `profil` -- ALTER TABLE `profil` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT pour la table `tache` -- ALTER TABLE `tache` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT pour la table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT pour la table `vehicule` -- ALTER TABLE `vehicule` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- Contraintes pour les tables déchargées -- -- -- Contraintes pour la table `commande_piece` -- ALTER TABLE `commande_piece` ADD CONSTRAINT `commande_piece_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `users` (`id`), ADD CONSTRAINT `commande_piece_ibfk_2` FOREIGN KEY (`id_piece`) REFERENCES `pieces` (`id`); -- -- Contraintes pour la table `commande_vehicule` -- ALTER TABLE `commande_vehicule` ADD CONSTRAINT `commande_vehicule_ibfk_1` FOREIGN KEY (`id_devis`) REFERENCES `devis` (`id`); -- -- Contraintes pour la table `devis` -- ALTER TABLE `devis` ADD CONSTRAINT `devis_ibfk_1` FOREIGN KEY (`id_client`) REFERENCES `client` (`id`), ADD CONSTRAINT `devis_ibfk_2` FOREIGN KEY (`id_user`) REFERENCES `users` (`id`), ADD CONSTRAINT `devis_ibfk_3` FOREIGN KEY (`id_vehicule`) REFERENCES `vehicule` (`id`); -- -- Contraintes pour la table `facture_devis` -- ALTER TABLE `facture_devis` ADD CONSTRAINT `facture_devis_ibfk_1` FOREIGN KEY (`id_devis`) REFERENCES `devis` (`id`); -- -- Contraintes pour la table `facture_fiche` -- ALTER TABLE `facture_fiche` ADD CONSTRAINT `facture_fiche_ibfk_1` FOREIGN KEY (`id_fiche`) REFERENCES `fiche` (`id`); -- -- Contraintes pour la table `fiche` -- ALTER TABLE `fiche` ADD CONSTRAINT `fiche_ibfk_1` FOREIGN KEY (`id_client`) REFERENCES `client` (`id`), ADD CONSTRAINT `fiche_ibfk_2` FOREIGN KEY (`id_user`) REFERENCES `users` (`id`), ADD CONSTRAINT `fiche_ibfk_3` FOREIGN KEY (`id_priorite`) REFERENCES `priorite` (`id`); -- -- Contraintes pour la table `profil_user` -- ALTER TABLE `profil_user` ADD CONSTRAINT `profil_user_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `users` (`id`), ADD CONSTRAINT `profil_user_ibfk_2` FOREIGN KEY (`id_profil`) REFERENCES `profil` (`id`); -- -- Contraintes pour la table `tache` -- ALTER TABLE `tache` ADD CONSTRAINT `tache_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `users` (`id`), ADD CONSTRAINT `tache_ibfk_2` FOREIGN KEY (`id_fiche`) REFERENCES `fiche` (`id`), ADD CONSTRAINT `tache_ibfk_3` FOREIGN KEY (`id_priorite`) REFERENCES `priorite` (`id`), ADD CONSTRAINT `tache_ibfk_4` FOREIGN KEY (`id_piece`) REFERENCES `pieces` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
ec3bbc96ba93cfd76580987b1b3d505fafb56a16
SQL
NikiYu812/hms
/sql/tb_sysuser.sql
UTF-8
997
2.71875
3
[]
no_license
/* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Version : 50527 Source Host : localhost:3306 Source Database : housingdb Target Server Type : MYSQL Target Server Version : 50527 File Encoding : 65001 Date: 2017-12-06 09:28:13 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `tb_sysuser` -- ---------------------------- DROP TABLE IF EXISTS `tb_sysuser`; CREATE TABLE `tb_sysuser` ( `id` varchar(4) NOT NULL DEFAULT '', `usename` varchar(10) DEFAULT NULL, `password` varchar(10) DEFAULT NULL, `last_login_time` varchar(20) DEFAULT NULL, `create_time` varchar(20) DEFAULT NULL, `isDelete` int(11) DEFAULT NULL, `remark` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tb_sysuser -- ---------------------------- INSERT INTO `tb_sysuser` VALUES ('0001', 'admin', 'admin11', null, null, '0', null);
true
a3e3282ef80134f810db82d2336cfb60a2009e00
SQL
xkapotis/SQL-Project
/Queries 3-4-5/Query i.sql
ISO-8859-7
529
3.40625
3
[]
no_license
select (m.Sname + ' ' + m.name ) [], p.code [ ] , p.Title [ ], CONVERT(varchar, p.Startdate, 103) [ ] , CONVERT(varchar, p.enddate, 103) [ ] from Projects p join Members m on p.Members_idMembers = m.idMembers join Project_status ps on p.Project_status_idProject_status = ps.idProject_status where m.Sname = '' and ps.Description = ''
true
5b983acb0578ca3a23c22f2591104e29f6317f32
SQL
yfheroku/dockCoin
/src/app/Api/ReadMe/coin.sql
UTF-8
2,395
3.515625
4
[]
no_license
#记录拉取记录的当前区块数/截止时间,供下次拉取使用 CREATE TABLE `symbol_recharge_block` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `block_num` int(15) DEFAULT '0', `symbol` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4; #记录对应币种生成的钱包地址 CREATE TABLE `user_address` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(50) DEFAULT '' COMMENT '会员编号', `address` varchar(255) DEFAULT '' COMMENT '钱包地址', `symbol` varchar(20) DEFAULT '' COMMENT '币种', `w_time` int(10) DEFAULT '0', `secret` int(10) DEFAULT '' COMMENT '钱包私钥', `certificate` text COMMENT '记录额外凭证', PRIMARY KEY (`id`), KEY `s_name` (`symbol`,`username`) USING BTREE ) ENGINE=MyISAM AUTO_INCREMENT=35 DEFAULT CHARSET=utf8mb4; #记录充币和提币的交易记录 CREATE TABLE `user_hash` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `symbol` varchar(20) DEFAULT NULL, `amount` double(30,8) DEFAULT NULL, `hash` varchar(255) DEFAULT NULL, `w_time` int(10) DEFAULT '0', `username` varchar(50) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, `status` tinyint(1) DEFAULT '0' COMMENT '状态 0确认中 1确认成功 -1交易失败', `destination` varchar(255) DEFAULT NULL, `currency` varchar(10) DEFAULT '''RMB''', `type` tinyint(1) DEFAULT '1' COMMENT '默认1 充值 2 提币', PRIMARY KEY (`id`), UNIQUE KEY `hash` (`hash`(191),`type`,`username`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4; #user_nonce表,记录当前的以太坊(及其代币)交易的nonce值 #[nonce值作为交易的唯一标识,只要保证Nonce值唯一,就不会出现重发情况] CREATE TABLE `user_nonce` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nonce` varchar(255) NOT NULL DEFAULT '0.00000000', `gasPrice` varchar(50) NOT NULL DEFAULT '0.00000000', `gasLimit` varchar(50) NOT NULL DEFAULT '0.00000000', `to` varchar(125) NOT NULL DEFAULT '', `value` varchar(50) NOT NULL DEFAULT '0', `data` text NOT NULL, `chainId` int(1) NOT NULL, `txid` int(11) DEFAULT '0', `txhash` varchar(255) DEFAULT '', `ten` varchar(255) DEFAULT '', `symbol` varchar(255) DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=utf8;
true
c1835961a0353e06f43a3644cc1c050de15e2443
SQL
rajeshghourvani/assessor
/assessorportal/AMPSQL/AMP/Packages/ZZ_AMP_UTIL.sql
UTF-8
5,711
3.390625
3
[]
no_license
-------------------------------------------------------- -- DDL for Package ZZ_AMP_UTIL -------------------------------------------------------- CREATE OR REPLACE EDITIONABLE PACKAGE "AMP"."ZZ_AMP_UTIL" AS /****************************************************************************** NAME: AMP_UTILS PURPOSE: REVISIONS: Ver Date Author Description --------- ---------- --------------- ------------------------------------ 1.0 3/10/2016 ANACHIMU 1. Created this package. 1.1 3/13/2016 MAZAR 2. Added new functions. ******************************************************************************/ SUBTYPE asmt_obj_addr_id is ASMT_OBJ_ADDR.ID%TYPE; SUBTYPE address_id is ADDRESSES.ID%TYPE; SUBTYPE address_city is ADDRESSES.CITY%TYPE; SUBTYPE address_mail_type is ASMT_OBJ_ADDR.SITUS_MAIL_TYPE%TYPE ; SUBTYPE addr_mail_change_date is ADDRESSES.mail_change_date%TYPE; subtype search_text_type is varchar2(120) not null; TYPE add_rt IS RECORD ( asmt_obj_addr_id ASMT_OBJ_ADDR.ID%TYPE , address_id ADDRESSES.ID%TYPE , address_city ADDRESSES.CITY%TYPE , address_mail_type ASMT_OBJ_ADDR.SITUS_MAIL_TYPE%TYPE , address_mail_change_date ADDRESSES.mail_change_date%TYPE ); TYPE add_recs IS TABLE OF add_rt; --in case we need to return table of records. TYPE t_ref is REF CURSOR; /*Description for get_current_address: This function returns the current address based on the ASMT_OBJ_ID and ADDRESS_TYPE entered. If ADDRESS_TYPE is null, the function automatically finds if it is listed as a Primary or Vicinity and list that information. USAGE for get_current_address: declare l_result AMP_UTIL.add_rt; begin l_result := AMP_UTIL.GET_CURRENT_ADDRESS(52180408); dbms_output.put_line(l_result.asmt_obj_addr_id); dbms_output.put_line(l_result.address_city); end; */ FUNCTION get_current_address(p_asmt_obj_id IN NUMBER, p_address_type IN varchar2 DEFAULT NULL) RETURN add_rt; /*Description for get_current_address_id: This function returns the current address ID based on the ASMT_OBJ_ID and ADDRESS_TYPE entered. If ADDRESS_TYPE is null, the function automatically finds if it is listed as a Primary or Vicinity and list that information. USAGE for get_current_address_id: DECLARE l_result NUMBER; BEGIN l_result := AMP_UTIL.get_current_address_id(52024132); DBMS_OUTPUT.PUT_LINE(l_result); END;*/ FUNCTION get_current_address_id( p_asmt_obj_id IN NUMBER, p_address_type IN VARCHAR2 DEFAULT NULL) RETURN NUMBER; /*Created by Joel Thompson Description for retrieve_rp_summary_item: This function returns information for a specific record from the rp_summary_vw VIEW based on the search criteria entered in the parameters. USAGE for retrieve_rp_summary_item: DECLARE v_rc sys_refcursor; l_row rp_summary_vw%ROWTYPE; BEGIN v_rc := amp_util.retrieve_rp_summary_item(52180408, null, null, null, null, null, null, null, null, null, null, null, null, null); LOOP FETCH v_rc INTO l_row; EXIT WHEN v_rc%NOTFOUND; -- Exit the loop when we've run out of data dbms_output.put_line('Row: '||v_rc%ROWCOUNT||' # '||l_row.ID||','||l_row.AIN); END LOOP; CLOSE v_rc; END; */ /* FUNCTION retrieve_rp_summary_item( p_AOID ASMT_OBJECTS.ID%TYPE, p_AIN ASMT_OBJECTS.AIN%TYPE, p_OWNER_NAME OWNERS.NAME%TYPE, p_LEGAL_DESC ASMT_OBJECTS.LEGAL_DESCRIPTION%TYPE, p_DBA OWNERSHIP_HISTORY.DBA%TYPE, p_STREET_NUMBER ADDRESSES.STREET_NUMBER%type, p_FRACTION ADDRESSES.FRACTION%TYPE, p_DIRECTION ADDRESSES.DIRECTION%TYPE, p_UNIT_NUMBER ADDRESSES.UNIT_NUMBER%TYPE, p_STREET ADDRESSES.STREET%TYPE, p_CITY ADDRESSES.CITY%TYPE, p_STATE ADDRESSES.STATE%TYPE, p_COUNTRY ADDRESSES.COUNTRY%TYPE, p_ZIP ADDRESSES.ZIP%TYPE ) RETURN T_REF ; */ /* Description for retrieve_rp_summary_item: This function returns the summary information for a specific record from the rp_summary_vw VIEW based on the AIN entered as parameter. USAGE for retrieve_rp_summary_item: var rc REFCURSOR; exec :rc := AMP_UTIL.retrieve_rp_summary_item('2004012022'); print rc; */ FUNCTION retrieve_rp_summary_item ( p_ain ASMT_OBJECTS.AIN%TYPE ) RETURN SYS_REFCURSOR; /* Description for retrieve_rp_summary_item: This function returns the summary list for search from the rp_summary_vw VIEW based on the search criteria entered in the parameters. USAGE: NOT DONE YET */ /*FUNCTION retrieve_rp_summary_list( p_AIN ASMT_OBJECTS.AIN%TYPE, p_OWNER_NAME OWNERS.NAME%TYPE, p_SITUS_ADDRESS ADDRESSES.STREET%TYPE, p_LEGAL_DESCRIPTION ASMT_OBJECTS.LEGAL_DESCRIPTION%TYPE, p_RECORD_NUMBER_BEGIN NUMBER, p_RECORD_NUMBER_END NUMBER ) RETURN SYS_REFCURSOR;*/ FUNCTION retrieve_rp_summary_list( p_AIN ASMT_OBJECTS.AIN%TYPE default null, p_OWNER_NAME OWNERS.NAME%TYPE default null, p_SITUS_ADDRESS ADDRESSES.STREET%TYPE default null, p_LEGAL_DESCRIPTION ASMT_OBJECTS.LEGAL_DESCRIPTION%TYPE default null, p_RECORD_NUMBER_BEGIN NUMBER default null, p_RECORD_NUMBER_END NUMBER default null ) RETURN SYS_REFCURSOR ; /*Description: This function retrieves real property info. USAGE: */ FUNCTION retrieve_real_property_info( p_AIN ASMT_OBJECTS.AIN%TYPE ) RETURN T_REF ; --END AMP_UTIL; /
true
39230bce018b0cbd0afc43c82fd82c22627110e3
SQL
jpschoen/SODA501_SP17
/la_blocks_wgs84_spatialjoin.sql
UTF-8
2,043
3.34375
3
[]
no_license
SELECT gid, statefp10, countyfp10, tractce10, blockce10, geoid10, name10, mtfcc10, ur10, uace10, uatype, funcstat10, aland10, awater10, intptlat10, intptlon10, geom FROM la_blocks_wgs84; COPY work_501 FROM 'F:\\6.gradcourse\\SoDA501\\work.csv' DELIMITER ',' CSV HEADER alter table home_501 ADD COLUMN geom geometry(POINT,4326); UPDATE home_501 SET geom = ST_SetSRID(ST_MakePoint(lon,lat),4326); select user_id, lon, lat, tw_time, geoid from tweets_p_t p1, county_wgs84 p2 where st_within (p1.geom, p2.geom) select geoid10, count(*) from home_501 p1, la_blocks_wgs84 p2 where st_within(p1.geom, p2.geom) group by geoid10 SELECT f_table_name, f_geometry_column, srid FROM geometry_columns; SELECT UpdateGeometrySRID('la_blocks_wgs84','geom',4326); create index aba on la_blocks_wgs84 using GIST (geom) create index abaa on home_501 using GIST (geom) CREATE INDEX jacksonco_streets_gix ON jacksonco_streets USING GIST (the_geom); alter table work_501 ADD COLUMN geom geometry(POINT,4326); UPDATE work_501 SET geom = ST_SetSRID(ST_MakePoint(lon,lat),4326); create index abaass on home_501 using GIST (geom) select geoid10, count(*) from work_501 p1, la_blocks_wgs84 p2 where st_within(p1.geom, p2.geom) group by geoid10 select geoid10, count(*) from (select distinct geoid10, userid from home_501 p1, la_blocks_wgs84 p2 where st_within(p1.geom, p2.geom)) a group by geoid10 select geoid10, count(*) from (select distinct geoid10, userid from home_501 p1, la_blocks_wgs84 p2 where st_within(p1.geom, p2.geom)) a group by geoid10 select geoid10, count(*) as usercnt from( select distinct on (userid) userid, geoid10, count(*) as freq from home_501 p1, la_blocks_wgs84 p2 where st_within(p1.geom, p2.geom) group by userid, geoid10 order by userid, freq) b group by geoid10 select geoid10, count(*) as usercnt from( select distinct on (userid) userid, geoid10, count(*) as freq from work_501 p1, la_blocks_wgs84 p2 where st_within(p1.geom, p2.geom) group by userid, geoid10 order by userid, freq) b group by geoid10
true
a105c8a13a63fdbfdf322b7e60f7b62b0cf45589
SQL
inest-us/db
/cms/GetArticleByID.sql
UTF-8
462
3.734375
4
[ "MIT" ]
permissive
ALTER PROCEDURE GetArticleByID ( @ArticleID int ) AS SET NOCOUNT ON SELECT a.ArticleID, a.AddedDate, a.AddedBy, a.CategoryID, a.Title, a.Abstract, a.Body, a.Country, a.State, a.City, a.ReleasedDate, a.ExpiredDate, a.Approved, a.Listed, a.CommentsEnabled, a.OnlyForMembers, a.ViewCount, a.Votes, a.TotalRating, c.Title as CategoryTitle FROM Articles a INNER JOIN Categories c ON a.CategoryID = c.CategoryID WHERE a.ArticleID = @ArticleID
true
d6cfb0eda719840b5a70b09f97fecfd7ed45c598
SQL
wsigma21/sql_exercises
/basic/question51.sql
UTF-8
327
2.96875
3
[]
no_license
-- 全てのゴール情報を出力してください。 -- ただし、オウンゴール(player_idがNULLのデータ)はIFNULL関数を使用してplayer_idを「9999」と表示してください。 select id, pairing_id, case when player_id is null then 9999 else player_id end as "player_id", goal_time from goals ;
true
9ff8b7a8196fcbeb24f2f6a77a34bc86627d6e35
SQL
AdamHood/RedshiftScripts
/AdminViews/v_get_users_in_group.sql
UTF-8
470
3.359375
3
[]
no_license
/********************************************************************************************** Purpose: View to get all users in a group History: 2013-10-29 jjschmit Created **********************************************************************************************/ CREATE OR REPLACE VIEW admin.v_get_users_in_group AS SELECT pg_group.groname ,pg_group.grosysid ,pg_user.* FROM pg_group, pg_user WHERE pg_user.usesysid = ANY(pg_group.grolist) ORDER BY 1,2 ;
true
2e39dc6612ed093c2b118f37a29c373d80f98ddc
SQL
4xpl0r3r-misc-repo/zjctf_2019_wannengmima
/files/html/db.sql
UTF-8
285
2.65625
3
[]
no_license
CREATE DATABASE ctf; USE ctf; CREATE TABLE `Users`( `username` VARCHAR(100) NOT NULL, `password` VARCHAR(100) NOT NULL, `id` INT UNSIGNED AUTO_INCREMENT, PRIMARY KEY ( `id`) )ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO Users(username,password) VALUES ('Admin','dmpJlsg2MbFiie8IIF2aSC9fish2UoFuQJHHE5qQcnA6iwIvbH');
true
21b51afc289c1e816943f50685d909244ae4539d
SQL
hjd7893git/fileTransfer
/src/main/sql/oracle/policy.sql
UTF-8
1,328
2.671875
3
[]
no_license
DROP TABLE "policy"; CREATE TABLE "policy" ( "id" NUMBER(20) VISIBLE NOT NULL , "name" VARCHAR2(256 BYTE) VISIBLE NOT NULL , "nodeid" NUMBER(20) VISIBLE NOT NULL , "path" VARCHAR2(1024 BYTE) VISIBLE NOT NULL , "enc" NUMBER(1) VISIBLE NOT NULL , "compress" NUMBER(1) VISIBLE NOT NULL , "sign" NUMBER(1) VISIBLE NOT NULL , "times" VARCHAR2(256 BYTE) VISIBLE NOT NULL , "extensions" VARCHAR2(256 BYTE) VISIBLE NOT NULL ) NOLOGGING NOCOMPRESS NOCACHE; ALTER TABLE "policy" ADD CHECK ("id" IS NOT NULL); ALTER TABLE "policy" ADD CHECK ("name" IS NOT NULL); ALTER TABLE "policy" ADD CHECK ("nodeid" IS NOT NULL); ALTER TABLE "policy" ADD CHECK ("path" IS NOT NULL); ALTER TABLE "policy" ADD CHECK ("enc" IS NOT NULL); ALTER TABLE "policy" ADD CHECK ("compress" IS NOT NULL); ALTER TABLE "policy" ADD CHECK ("sign" IS NOT NULL); ALTER TABLE "policy" ADD CHECK ("times" IS NOT NULL); ALTER TABLE "policy" ADD CHECK ("extensions" IS NOT NULL); ALTER TABLE "policy" ADD PRIMARY KEY ("id"); INSERT INTO "policy" VALUES ('1', 'policy01', '2', '/test1', '1', '1', '1', '*', '.doc,.txt,.docx'); INSERT INTO "policy" VALUES ('2', 'policy02', '2', '/test', '1', '1', '1', '12:30', '.tar,.zip,.tar.gz,.tgz,.jar'); INSERT INTO "policy" VALUES ('3', 'policy03', '2', '/test02', '0', '0', '0', '00:30,06:30,12:30,18:30', '*');
true
bae4f8fb74f5f686682432b51827de81c632ad21
SQL
eastar93/MySQL
/OurJspProject.sql
UTF-8
1,154
3.125
3
[]
no_license
CREATE TABLE users( uid varchar(20) primary key, upw varchar(20) not null, uname varchar(10) not null, uemail varchar(45) not null, subject varchar(50), qcode integer DEFAULT 0, point integer DEFAULT 0, tier integer DEFAULT 0 ); INSERT into users VALUES('test', '1234', 'user', 'user@test.com', 'html, java', 0, 0, 0, 0); SELECT * from users; DROP TABLE answer; create table question( qcode integer primary key, question varchar(60), qtcount integer DEFAULT 0 ); CREATE TABLE solve ( auto_acode INT PRIMARY KEY NOT NULL AUTO_INCREMENT, qcode INT NOT NULL, answer VARCHAR(30) NULL, solvedate DATETIME NOT NULL ); create table correct( ccode integer primary key, correct varchar(30) ); CREATE TABLE answer ( auto_acode INT PRIMARY KEY NOT NULL AUTO_INCREMENT, qcode INT NOT NULL, answer VARCHAR(30) NULL, solvedate DATETIME NOT NULL ); CREATE TABLE board ( no INT primary key not null AUTO_INCREMENT, btype varchar(20) not null, btitle varchar(45) not null, bwriter varchar(10) not null, bcontent varchar(2000) not null, bhit INT not null DEFAULT 0 );
true
847d25d6b29f4433e980d5e6841e189025f12d9c
SQL
FeiBaliou/private-school-management-system
/Database/DB_SchoolManagementSystem.sql
UTF-8
15,700
3.890625
4
[]
no_license
CREATE DATABASE schoolmanagementsystem; use schoolmanagementsystem; CREATE TABLE IF NOT EXISTS `courses` ( `id` INT NOT NULL AUTO_INCREMENT, `title` varchar(45) NOT NULL, `stream` varchar(45) NOT NULL, `type` varchar(45) NOT NULL, `startdate` DATE, `enddate` DATE, PRIMARY KEY (`id`) ); -- ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `students` ( `id` INT NOT NULL AUTO_INCREMENT, `fname` varchar(45) NOT NULL, `lname` varchar(45) NOT NULL, `dob` DATE NOT NULL, `tuitionfees` DECIMAL(6,2), PRIMARY KEY (`id`) ); -- ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `trainers` ( `id` INT NOT NULL AUTO_INCREMENT, `fname` varchar(45) NOT NULL, `lname` varchar(45) NOT NULL, `subject` varchar(45) NOT NULL, PRIMARY KEY (`id`) ); -- ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `assignments` ( `id` INT NOT NULL AUTO_INCREMENT, `title` varchar(45) NOT NULL, `description` varchar(45) NOT NULL, `subdate` DATE NOT NULL, `oralmark` DECIMAL(3,1) NOT NULL, `totalmark` DECIMAL(4,1) NOT NULL, UNIQUE (title,description), PRIMARY KEY (`id`) ); -- ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `enrollments` ( `id` int NOT NULL AUTO_INCREMENT, `sid` int DEFAULT NULL, `cid` int DEFAULT NULL, PRIMARY KEY (id), UNIQUE (`sid`,`cid`), KEY `fk_enrollments_cid_courses_id_idx` (`cid`), KEY `fk_enrollments_sid_students_id_idx` (`sid`), CONSTRAINT `fk_enrollments_cid_courses_id` FOREIGN KEY (`cid`) REFERENCES `courses` (`id`), CONSTRAINT `fk_enrollments_sid_students_id` FOREIGN KEY (`sid`) REFERENCES `students` (`id`) ); -- ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `enrollmentassignments` ( `id` int NOT NULL AUTO_INCREMENT, `eid` int DEFAULT NULL, `aid` int DEFAULT NULL, oralmark DECIMAL(3,1) DEFAULT NULL, totalmark DECIMAL(4,1) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE(`eid`,`aid`), KEY `fk_enrollmentassignments_eid_enrollments_id_idx` (`eid`), KEY `fk_enrollmentassignments_aid_assignments_id_idx` (`aid`), CONSTRAINT `fk_enrollmentassignments_aid_assignments_id` FOREIGN KEY (`aid`) REFERENCES `assignments` (`id`), CONSTRAINT `fk_enrollmentassignments_eid_enrollments_id_idx` FOREIGN KEY (`eid`) REFERENCES `enrollments` (`id`) ); -- ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `enrollmentstrainers` ( `id` int NOT NULL AUTO_INCREMENT, `eid` int DEFAULT NULL, `tid` int DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE(`eid`,`tid`), KEY `fk_enrollmentstrainers_eid_courses_id_idx` (`eid`), KEY `fk_enrollmentstrainers_tid_trainers_id_idx` (`tid`), CONSTRAINT `fk_enrollmentstrainers_tid_trainers_id_idx` FOREIGN KEY (`tid`) REFERENCES `trainers` (`id`), CONSTRAINT `fk_enrollmentstrainers_eid_courses_id_idx` FOREIGN KEY (`eid`) REFERENCES `courses` (`id`) ); -- ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- Data for Courses INSERT IGNORE INTO courses (id,title,stream,type,startdate,enddate) VALUES (1,'CB12','Java','Part Time','2020-09-30','2021-04-30'), (2,'CB12','Java','Full Time','2020-09-25','2020-12-30'), (3,'CB12','C#','Part Time','2020-09-26','2021-04-03'), (4,'CB12','Pyhton','Part Time','2020-10-20','2021-03-30'), (5,'CB12','Pyhton','Full Time','2020-10-30','2020-12-15'); -- Data for Students INSERT IGNORE INTO students (id,fname,lname,dob,tuitionfees) VALUES (1,'Zebulen', 'Purdom', '1985-05-10', 1600.50), (2,'Haily', 'Picton', '1987-08-20', 1700.00), (3,'Carma', 'Pollington', '1997-08-10', 2100.00), (4,'Nigel', 'Verrill', '1996-04-01', 2000.00), (5,'Brear', 'Reston', '1987-01-29', 1300.00), (6,'Cirstoforo', 'Donkersley', '1989-02-11', 1250.00), (7,'Daphna', 'Mycroft', '1990-10-19', 1200.00), (8,'Stacy', 'MacCarter', '1983-04-05', 1230.00), (9,'Sarina', 'Mechem', '1990-01-31', 2200.00), (10,'Heywood', 'Lomasny', '1992-04-26', 2050.50), (11,'Celie', 'Caspell', '1994-07-18', 1700.00), (12,'Knox', 'Vernham', '1997-03-27', 2300.00), (13,'Thibaud', 'Moyler', '1992-07-09', 1000.00), (14,'Theo', 'Chorlton', '1996-08-11', 2500.00), (15,'Karena', 'Gertz', '1986-01-02', 1750.50), (16,'Karon', 'Langland', '1983-03-21', 1270.00), (17,'Brett', 'Camillo', '2000-02-26', 2400.00), (18,'Sally', 'Pixton', '1988-12-20', 1600.00), (19,'Lorrin', 'Bremner', '1985-07-07', 1900.00), (20,'Dasia', 'O''Dennehy', '1983-03-06', 1950.00); -- Data for Trainers INSERT IGNORE INTO trainers (id,fname,lname,subject) VALUES (1,'Di', 'Kett','MySql'), (2,'Dinah', 'Madle','Front-end'), (3,'Jeremie', 'Tunder','Back-end'), (4,'Petty', 'Pordall','Front-end'), (5,'Mitzi', 'Van Arsdall','Back-end'), (6,'Lyell', 'Stapele','Back-end'), (7,'Konrad', 'Philliskirk','MySql'), (8,'Kassi', 'Baskwell','MySql'), (9,'Filippo', 'Drawmer','Front-end'), (10,'Gabe', 'Shafier','Front-end'), (11,'Gaylord', 'Riguard','Back-end'); -- Data for Assignments INSERT IGNORE INTO assignments (id,title,description,subdate,oralmark,totalmark) VALUES (1,'Individual Project Part A','School Management System','2020-10-10',20,100), (2,'Individual Project Part B','Database for School Management System','2020-11-10',20,100), (3,'Individual Project Part C','Web App - School Management System','2020-11-10',20,100), (4,'Team Project Part A','CRM for small Business','2020-12-10',20,100), (5,'Team Project Part B','Web App - CRM for small Business','2020-10-10',20,100); -- Data for enrollments INSERT IGNORE INTO enrollments (id,sid,cid) VALUES (1,(SELECT id FROM students WHERE id=1),(SELECT id FROM courses WHERE id=1)), (2,(SELECT id FROM students WHERE id=2),(SELECT id FROM courses WHERE id=4)), (3,(SELECT id FROM students WHERE id=3),(SELECT id FROM courses WHERE id=5)), (4,(SELECT id FROM students WHERE id=4),(SELECT id FROM courses WHERE id=5)), (5,(SELECT id FROM students WHERE id=5),(SELECT id FROM courses WHERE id=2)), (6,(SELECT id FROM students WHERE id=6),(SELECT id FROM courses WHERE id=3)), (7,(SELECT id FROM students WHERE id=7),(SELECT id FROM courses WHERE id=3)), (8,(SELECT id FROM students WHERE id=8),(SELECT id FROM courses WHERE id=1)), (9,(SELECT id FROM students WHERE id=9),(SELECT id FROM courses WHERE id=4)), (10,(SELECT id FROM students WHERE id=10),(SELECT id FROM courses WHERE id=5)), (11,(SELECT id FROM students WHERE id=10),(SELECT id FROM courses WHERE id=1)), (12,(SELECT id FROM students WHERE id=11),(SELECT id FROM courses WHERE id=1)), (13,(SELECT id FROM students WHERE id=12),(SELECT id FROM courses WHERE id=2)), (14,(SELECT id FROM students WHERE id=12),(SELECT id FROM courses WHERE id=3)), (15,(SELECT id FROM students WHERE id=1),(SELECT id FROM courses WHERE id=4)), (16,(SELECT id FROM students WHERE id=13),(SELECT id FROM courses WHERE id=1)), (17,(SELECT id FROM students WHERE id=14),(SELECT id FROM courses WHERE id=1)), (18,(SELECT id FROM students WHERE id=15),(SELECT id FROM courses WHERE id=2)), (19,(SELECT id FROM students WHERE id=16),(SELECT id FROM courses WHERE id=2)), (20,(SELECT id FROM students WHERE id=17),(SELECT id FROM courses WHERE id=3)), (21,(SELECT id FROM students WHERE id=18),(SELECT id FROM courses WHERE id=2)), (22,(SELECT id FROM students WHERE id=18),(SELECT id FROM courses WHERE id=4)), (23,(SELECT id FROM students WHERE id=19),(SELECT id FROM courses WHERE id=1)), (24,(SELECT id FROM students WHERE id=9),(SELECT id FROM courses WHERE id=5)), (25,(SELECT id FROM students WHERE id=1),(SELECT id FROM courses WHERE id=1)); -- Data for enrollmentassignments INSERT IGNORE INTO enrollmentassignments (id,eid,aid,oralmark,totalmark) VALUES (1,(SELECT id from enrollments WHERE id =1),(SELECT id FROM assignments WHERE id =1),15,80), (2,(SELECT id from enrollments WHERE id =1),(SELECT id FROM assignments WHERE id =2),10,70), (3,(SELECT id from enrollments WHERE id =1),(SELECT id FROM assignments WHERE id =3),20,80), (4,(SELECT id from enrollments WHERE id =2),(SELECT id FROM assignments WHERE id =1),10,65), (5,(SELECT id from enrollments WHERE id =2),(SELECT id FROM assignments WHERE id =2),12,55), (6,(SELECT id from enrollments WHERE id =2),(SELECT id FROM assignments WHERE id =4),13,90), (7,(SELECT id from enrollments WHERE id =3),(SELECT id FROM assignments WHERE id =1),17,45), (8,(SELECT id from enrollments WHERE id =3),(SELECT id FROM assignments WHERE id =2),20,100), (9,(SELECT id from enrollments WHERE id =3),(SELECT id FROM assignments WHERE id =3),15,95), (10,(SELECT id from enrollments WHERE id =3),(SELECT id FROM assignments WHERE id =4),18,88), (11,(SELECT id from enrollments WHERE id =3),(SELECT id FROM assignments WHERE id =5),19,90); INSERT IGNORE INTO enrollmentassignments (id,eid,aid) VALUES (12,(SELECT id from enrollments WHERE id =4),(SELECT id FROM assignments WHERE id =1)), (13,(SELECT id from enrollments WHERE id =4),(SELECT id FROM assignments WHERE id =2)), (14,(SELECT id from enrollments WHERE id =5),(SELECT id FROM assignments WHERE id =1)), (15,(SELECT id from enrollments WHERE id =5),(SELECT id FROM assignments WHERE id =2)), (16,(SELECT id from enrollments WHERE id =1),(SELECT id FROM assignments WHERE id =1)); -- Data for enrollmentstrainers INSERT IGNORE INTO enrollmentstrainers(id,eid,tid) VALUES (1,(SELECT id from courses WHERE id =1),(SELECT id FROM trainers WHERE id =3)), (2,(SELECT id from courses WHERE id =1),(SELECT id FROM trainers WHERE id =2)), (3,(SELECT id from courses WHERE id =1),(SELECT id FROM trainers WHERE id =10)), (4,(SELECT id from courses WHERE id =2),(SELECT id FROM trainers WHERE id =3)), (5,(SELECT id from courses WHERE id =2),(SELECT id FROM trainers WHERE id =4)), (6,(SELECT id from courses WHERE id =3),(SELECT id FROM trainers WHERE id =3)), (7,(SELECT id from courses WHERE id =3),(SELECT id FROM trainers WHERE id =7)), (8,(SELECT id from courses WHERE id =3),(SELECT id FROM trainers WHERE id =8)), (9,(SELECT id from courses WHERE id =4),(SELECT id FROM trainers WHERE id =9)), (10,(SELECT id from courses WHERE id =4),(SELECT id FROM trainers WHERE id =1)), (11,(SELECT id from courses WHERE id =4),(SELECT id FROM trainers WHERE id =5)), (12,(SELECT id from courses WHERE id =5),(SELECT id FROM trainers WHERE id =5)), (13,(SELECT id from courses WHERE id =4),(SELECT id FROM trainers WHERE id =6)), (14,(SELECT id from courses WHERE id =1),(SELECT id FROM trainers WHERE id =3)); -- List with Students DELIMITER // CREATE PROCEDURE getAllStudents() BEGIN SELECT students.id, students.fname as `First Name`,students.lname as `Last Name`,students.dob as `Date Of Birth`, students.tuitionfees as `Tuition Fees` FROM students; END // DELIMITER ; CALL getAllStudents(); -- List with Courses DELIMITER // CREATE PROCEDURE getAllCourses() BEGIN SELECT courses.id, courses.title as `Title`, courses.stream as `Stream`, courses.type , courses.startdate as `Start Date`, courses.enddate as `End Date` FROM courses; END // DELIMITER ; CALL getAllCourses(); -- List with Assignments DELIMITER // CREATE PROCEDURE getAllAssignments() BEGIN SELECT assignments.id, assignments.title as `Title`, assignments.description as `Description`, assignments.subdate as `Submission Date` , assignments.oralmark as `Oral Mark`, assignments.totalmark as `Total Mark` FROM assignments; END // DELIMITER ; CALL getAllAssignments(); -- List with Trainers DELIMITER // CREATE PROCEDURE getAllTrainers() BEGIN SELECT trainers.id, trainers.fname as `First Name`, trainers.lname as `Last Name`, trainers.subject as `Subject` FROM trainers; END // DELIMITER ; CALL getAllTrainers(); -- List of Studens per Course DELIMITER // CREATE PROCEDURE getStudentsPerCourse() BEGIN SELECT enrollments.id, courses.title AS `Title`,courses.stream AS `Stream`,courses.type,students.fname AS `First Name`, students.lname AS `Last Name` FROM students INNER JOIN enrollments ON enrollments.sid = students.id INNER JOIN courses ON courses.id = enrollments.cid group by enrollments.id order by courses.id; END // DELIMITER ; CALL getStudentsPerCourse(); DELIMITER // CREATE PROCEDURE getStudentsPerCoursebyId() BEGIN SELECT enrollments.id, courses.title AS `Title`,courses.stream AS `Stream`,courses.type,students.fname AS `First Name`, students.lname AS `Last Name` FROM students INNER JOIN enrollments ON enrollments.sid = students.id INNER JOIN courses ON courses.id = enrollments.cid group by enrollments.id order by enrollments.id; END // DELIMITER ; CALL getStudentsPerCoursebyId(); -- All the trainers per course DELIMITER // CREATE PROCEDURE getTrainersPerCourse() BEGIN SELECT enrollmentstrainers.id,courses.title AS `Title`,courses.stream AS `Stream`,courses.type,trainers.fname AS `First Name`, trainers.lname AS `Last Name`, trainers.subject as `Subject` FROM trainers INNER JOIN enrollmentstrainers ON enrollmentstrainers.tid = trainers.id INNER JOIN courses ON courses.id = enrollmentstrainers.eid group by enrollmentstrainers.id order by courses.id; END // DELIMITER ; CALL getTrainersPerCourse(); -- All the assignments per course DELIMITER // CREATE PROCEDURE getAssignmentsPerCourse() BEGIN SELECT DISTINCT courses.title AS `Title`,courses.stream AS `Stream`,courses.type,assignments.title AS `Assignment Title`, assignments.description as `Description` FROM enrollmentassignments INNER JOIN enrollments ON enrollments.id = enrollmentassignments.eid INNER JOIN assignments ON enrollmentassignments.aid = assignments.id INNER JOIN courses ON courses.id = enrollments.cid ORDER BY courses.id; END // DELIMITER ; CALL getAssignmentsPerCourse(); -- All the assignments per course per student DELIMITER // CREATE PROCEDURE getAssignmentsPerCoursePerStudent() BEGIN SELECT enrollmentassignments.id,students.fname AS `First Name` ,students.lname AS `Last Name`,courses.title AS `Course Title`, courses.stream AS `Course Stream`,courses.type AS `Course Type`,assignments.title AS `Assignment Title`, enrollmentassignments.oralmark AS `Oral Mark`,enrollmentassignments.totalmark AS `Total Mark` FROM students INNER JOIN enrollments ON students.id = enrollments.sid INNER JOIN enrollmentassignments ON enrollmentassignments.eid = enrollments.id inner join courses on courses.id = enrollments.cid inner join assignments on enrollmentassignments.aid = assignments.id -- group by enrollmentassignments.id order by students.id; END // DELIMITER ; CALL getAssignmentsPerCoursePerStudent(); -- All the assignments per course per student without grades DELIMITER // CREATE PROCEDURE getAssignmentsPerCoursePerStudentNullGrades() BEGIN SELECT enrollmentassignments.id,students.fname AS `First Name` ,students.lname AS `Last Name`,courses.title AS `Course Title`, courses.stream AS `Course Stream`,courses.type AS `Course Type`,assignments.title AS `Assignment Title`, enrollmentassignments.oralmark AS `Oral Mark`,enrollmentassignments.totalmark AS `Total Mark` FROM students INNER JOIN enrollments ON students.id = enrollments.sid INNER JOIN enrollmentassignments ON enrollmentassignments.eid = enrollments.id inner join courses on courses.id = enrollments.cid inner join assignments on enrollmentassignments.aid = assignments.id where enrollmentassignments.oralmark IS NULL and enrollmentassignments.totalmark IS NULL order by students.id; END // DELIMITER ; CALL getAssignmentsPerCoursePerStudentNullGrades(); -- A list of students that belong to more than one courses DELIMITER // CREATE PROCEDURE getStudentsWithMultipleCourses() BEGIN SELECT students.fname as `First Name`,students.lname as `Last Name`,count(enrollments.sid) as ` Enrollments` FROM students INNER JOIN enrollments ON enrollments.sid = students.id group by students.id having count(enrollments.sid)>1; END // DELIMITER ; CALL getStudentsWithMultipleCourses();
true
405157288a2f1b1fead67d57da8b38d6afaab91c
SQL
tanzhiyihuijian/ssm-template
/src/main/resources/sql/tables.sql
UTF-8
456
2.8125
3
[]
no_license
DROP DATABASE IF EXISTS ssh_template; CREATE DATABASE IF NOT EXISTS ssh_template; USE ssh_template; CREATE TABLE user ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(30), password VARCHAR(20) ); INSERT INTO user (name, password) VALUES ('小明', '123456789'); INSERT INTO user (name, password) VALUES ('小花', '135792468'); INSERT INTO user (name, password) VALUES ('小芳', '147258369'); UPDATE user SET name = '小明' WHERE id = 1;
true
a478bdc20bc1991135d3a31d0e46fb5e391cbe92
SQL
emnbdx/EMToolBox
/EMToolBox/Mail/create.sql
UTF-8
11,222
3.546875
4
[]
no_license
CREATE DATABASE EMMAIL; USE EMMAIL; CREATE TABLE PATTERN( ID int identity(1,1), NAME varchar(255) not null, CONTENT varchar(255) not null, HTML bit not null, CONSTRAINT [PK_PATTERN] PRIMARY KEY CLUSTERED ([ID] ASC), CONSTRAINT [IX_PATTERN] UNIQUE NONCLUSTERED ([NAME] ASC) ); CREATE TABLE QUEUE( ID int identity(1,1), PATTERN_ID int not null, [TO] varchar(255) not null, SUBJECT varchar(255) not null, BODY varchar(255) not null, CREATIONDATE datetime2(7) null, SENDDATE datetime2(7) null, SEND bit not null DEFAULT 0, CONSTRAINT [PK_QUEUE] PRIMARY KEY CLUSTERED ([ID] ASC), FOREIGN KEY (PATTERN_ID) REFERENCES PATTERN(ID) ); CREATE TABLE SERVER( ID int identity(1,1), IP varchar(255) not null, LOGIN varchar(255) not null, PASSWORD varchar(255) null, PORT int not null, SSL bit not null, ENABLE bit not null DEFAULT 1, CONSTRAINT [PK_SERVER] PRIMARY KEY CLUSTERED ([ID] ASC) ); UPDATE PATTERN SET CONTENT = '<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>{Title}</title> <style type="text/css"> @import url(http://fonts.googleapis.com/css?family=Lato); </style> </head> <body style="font-family: Lato, sans-serif; font-weight: 500;"> <div style="width: 600px; margin: 0 auto;"> <div style="background-color: #0073a3; border-top-left-radius: 4px; border-top-right-radius: 4px; padding: 20px; color: #FFF; font-size: 20px;"> {Title} </div> <div style="border: solid #ccc; border-width: 0 1px 1px 1px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; padding: 20px; font-size: 16px;"> Afin de valider votre inscription, merci de cliquer sur le lien suivant: <a href="http://lbcalerter.com/Account/RegisterConfirmation/{Token}"> http://lbcalerter.com/Account/RegisterConfirmation </a> </div> <div style="text-align: center; font-size: 10px;"> Vous recevez cet email car vous êtes inscrit sur <a href="http://lbcalerter.com" target="_blank">LBCAlerter</a>.<br /> Si vous recevez trop d''emails, connectez-vous à votre espace pour modifier vos recherches. </div> </div> </body> </html>' WHERE NAME = 'LBC_CONFIRMATION' UPDATE PATTERN SET CONTENT = '<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>{Title}</title> <style type="text/css"> @import url(http://fonts.googleapis.com/css?family=Lato); </style> </head> <body style="font-family: Lato, sans-serif; font-weight: 500;"> <div style="width: 600px; margin: 0 auto;"> <div style="background-color: #0073a3; border-top-left-radius: 4px; border-top-right-radius: 4px; padding: 20px; color: #FFF; font-size: 20px;"> {Title} </div> <div style="border: solid #ccc; border-width: 0 1px 1px 1px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; padding: 20px; font-size: 16px;"> Afin de réinitialiser votre mot de passe, merci de cliquer sur le lien suivant: <a href="http://lbcalerter.com/Account/ResetPasswordConfirmation/{Token}"> http://lbcalerter.com/Account/ResetPasswordConfirmation </a> </div> <div style="text-align: center; font-size: 10px;"> Vous recevez cet email car vous êtes inscrit sur <a href="http://lbcalerter.com" target="_blank">LBCAlerter</a>.<br /> Si vous recevez trop d''emails, connectez-vous à votre espace pour modifier vos recherches. </div> </div> </body> </html>' WHERE NAME = 'LBC_RESET' -- Pattern de base UPDATE PATTERN SET CONTENT = '<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>{Title}</title> <style type="text/css"> @import url(http://fonts.googleapis.com/css?family=Lato); </style> </head> <body style="font-family: Lato, sans-serif; font-weight: 500;"> <div style="width: 600px; margin: 0 auto;"> <div style="background-color: #0073a3; border-top-left-radius: 4px; border-top-right-radius: 4px; padding: 20px; color: #FFF; font-size: 20px;"> {Title} </div> <div style="border: solid #ccc; border-width: 0 1px 1px 1px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; padding: 20px; font-size: 16px;"> Mise en ligne le {Date}<br /> {Contents>Place}<br /> {Contents>Price}<br /><br /> <a href="{Url}" target="_blank"> <img src="{Contents>PictureUrl}" alt="{Title}" style="width:160px; height: 120px;" /> </a> </div> <div style="text-align: center; font-size: 10px;">Vous recevez cet email car vous êtes inscrit sur <a href="http://lbcalerter.com" target="_blank">LBCAlerter</a>.<br /> Si vous recevez trop d''emails, connectez-vous à votre espace pour modifier vos recherches, ou cliquez <a href="http://lbcalerter.com/Search/Disable?id={SearchId}&adId={Id}" target="_blank">ici</a> pour désactiver cette alerte. </div> </div> </body> </html>' WHERE NAME = 'LBC_AD' UPDATE PATTERN SET CONTENT = '<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>{Title}</title> <style type="text/css"> @import url(http://fonts.googleapis.com/css?family=Lato); </style> </head> <body style="font-family: Lato, sans-serif; font-weight: 500;"> <div style="width: 600px; margin: 0 auto;"> <div style="background-color: #0073a3; border-top-left-radius: 4px; border-top-right-radius: 4px; padding: 20px; color: #FFF; font-size: 20px;"> {Title} </div> <div style="border: solid #ccc; border-width: 0 1px 1px 1px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; padding: 20px; font-size: 16px; "> Nombre d''annonces: {AdCount}<br /> Nombre de recherches: {AttemptCount} (1 toutes les {AttemptCadence} mins)<br /><br /> Liste des annonces du jour: {Ads} </div> <div style="text-align: center; font-size: 10px;"> Vous recevez cet email car vous êtes inscrit sur <a href="http://lbcalerter.com" target="_blank">LBCAlerter</a>.<br /> Si vous recevez trop d''emails, connectez-vous à votre espace pour modifier vos recherches, ou cliquez <a href="http://lbcalerter.com/Search/Disable?id={Id}&adId={AdId}" target="_blank">ici</a> pour désactiver cette alerte. </div> </div> </body> </html>' WHERE NAME = 'LBC_RECAP' UPDATE PATTERN SET CONTENT = '<span style="font-weight: bold; display:block; padding: 20px;">{Title}</span><br /> Mise en ligne le {Date}<br /> {Contents>Place}<br /> {Contents>Price}<br /><br /> <a href="{Url}" target="_blank"> <img src="{Contents>PictureUrl}" alt="{Title}" style="width:160px; height: 120px;" /> </a>' WHERE NAME = 'LBC_RECAP_AD' -- Pattern complet UPDATE PATTERN SET CONTENT = '<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>{Title}</title> <style type="text/css"> @import url(http://fonts.googleapis.com/css?family=Lato); </style> </head> <body style="font-family: Lato, sans-serif; font-weight: 500;"> <div style="width: 600px; margin: 0 auto;"> <div style="background-color: #0073a3; border-top-left-radius: 4px; border-top-right-radius: 4px; padding: 20px; color: #FFF; font-size: 20px;"> {Title} </div> <div style="border: solid #ccc; border-width: 0 1px 1px 1px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; padding: 20px; font-size: 16px;"> Mise en ligne le {Date}, par <a href="{Contents>ContactUrl}">{Contents>Name}</a> [Contents>Phone](<img src="{Contents>Phone}" alt="telephone"/>)[/Contents>Phone]<br /><br /> <a href="{Url}" target="_blank"> #Contents>PictureUrl#<img src="{Contents>PictureUrl}" alt="{Title}" style="width:160px; height: 120px;" />#/Contents>PictureUrl# </a><br /> #Contents>Param#{Contents>Param}<br />#/Contents>Param#<br /> [Contents>Latitude]<a href="http://maps.google.com/maps?q={Contents>Latitude},{Contents>Longitude}" target="_blank">Voir sur une carte</a><br /><br />[/Contents>Latitude] Description:<br /> {Contents>Description} </div> <div style="text-align: center; font-size: 10px;">Vous recevez cet email car vous êtes inscrit sur <a href="http://lbcalerter.com" target="_blank">LBCAlerter</a>.<br /> Si vous recevez trop d''emails, connectez-vous à votre espace pour modifier vos recherches, ou cliquez <a href="http://lbcalerter.com/Search/Disable?id={SearchId}&adId={Id}" target="_blank">ici</a> pour désactiver cette alerte. </div> </div> </body> </html>' WHERE NAME = 'LBC_AD_FULL' UPDATE PATTERN SET CONTENT = '<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>{Title}</title> <style type="text/css"> @import url(http://fonts.googleapis.com/css?family=Lato); </style> </head> <body style="font-family: Lato, sans-serif; font-weight: 500;"> <div style="width: 600px; margin: 0 auto;"> <div style="background-color: #0073a3; border-top-left-radius: 4px; border-top-right-radius: 4px; padding: 20px; color: #FFF; font-size: 20px;"> {Title} </div> <div style="border: solid #ccc; border-width: 0 1px 1px 1px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; padding: 20px; font-size: 16px; "> Nombre d''annonces: {AdCount}<br /> Nombre de recherches: {AttemptCount} (1 toutes les {AttemptCadence} mins)<br /><br /> Liste des annonces du jour: {Ads} </div> <div style="text-align: center; font-size: 10px;"> Vous recevez cet email car vous êtes inscrit sur <a href="http://lbcalerter.com" target="_blank">LBCAlerter</a>.<br /> Si vous recevez trop d''emails, connectez-vous à votre espace pour modifier vos recherches, ou cliquez <a href="http://lbcalerter.com/Search/Disable?id={Id}&adId={AdId}" target="_blank">ici</a> pour désactiver cette alerte. </div> </div> </body> </html>' WHERE NAME = 'LBC_RECAP_FULL' UPDATE PATTERN SET CONTENT = '<span style="font-weight: bold; display:block; padding: 20px;">{Title}</span><br /> Mise en ligne le {Date}, par <a href="{Contents>ContactUrl}">{Contents>Name}</a> [Contents>Phone](<img src="{Contents>Phone}" alt="telephone"/>)[/Contents>Phone]<br /><br /> <a href="{Url}" target="_blank"> #Contents>PictureUrl#<img src="{Contents>PictureUrl}" alt="{Title}" style="width:160px; height: 120px;" />#/Contents>PictureUrl# </a><br /> #Contents>Param#{Contents>Param}<br />#/Contents>Param#<br /> [Contents>Latitude]<a href="http://maps.google.com/maps?q={Contents>Latitude},{Contents>Longitude}" target="_blank">Voir sur une carte</a><br /><br />[/Contents>Latitude] Description:<br /> {Contents>Description}' WHERE NAME = 'LBC_RECAP_AD_FULL'
true
26548db5a1f7baf8dfc667db80fe5fe8aa0e5ba4
SQL
ToborTheGreat/Repository01
/toolkit.clusters_audit.sql
UTF-8
1,583
2.875
3
[]
no_license
-- -- PostgreSQL database dump -- SET statement_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = off; SET check_function_bodies = false; SET client_min_messages = warning; SET escape_string_warning = off; SET search_path = toolkit, pg_catalog; DROP INDEX toolkit.clusters_audit_idx2; DROP INDEX toolkit.clusters_audit_idx1; DROP INDEX toolkit.clusters_audit_idx; DROP TABLE toolkit.clusters_audit; SET search_path = toolkit, pg_catalog; SET default_tablespace = p2_toolkitdata; SET default_with_oids = false; -- -- Name: clusters_audit; Type: TABLE; Schema: toolkit; Owner: -; Tablespace: p2_toolkitdata -- CREATE TABLE clusters_audit ( market character varying(50) NOT NULL, cascade_id character varying(30) NOT NULL, cluster character varying(50) NOT NULL, cluster_group character varying(20) NOT NULL, last_updated timestamp without time zone, trans_type character varying(10), modified_by character varying(100) ); -- -- Name: clusters_audit_idx; Type: INDEX; Schema: toolkit; Owner: -; Tablespace: p2_toolkitdata -- CREATE INDEX clusters_audit_idx ON clusters_audit USING btree (market, cluster); -- -- Name: clusters_audit_idx1; Type: INDEX; Schema: toolkit; Owner: -; Tablespace: p2_toolkitdata -- CREATE INDEX clusters_audit_idx1 ON clusters_audit USING btree (cascade_id); -- -- Name: clusters_audit_idx2; Type: INDEX; Schema: toolkit; Owner: -; Tablespace: p2_toolkitdata -- CREATE INDEX clusters_audit_idx2 ON clusters_audit USING btree (cluster_group); -- -- PostgreSQL database dump complete --
true
527fe860b86557424ec9086c156f78f2eaed5f66
SQL
JoaoOliveiraFrade/sgqLoader
/SGQ_ALM_Projetos_Console/sql/ALM_CTs_Qte_Reteste.sql
UTF-8
1,132
3.890625
4
[]
no_license
update alm_cts set alm_cts.Qte_Reteste = Aux.Reteste from (select Subprojeto, Entrega, CT, count(*) as Reteste from (select dt.Subprojeto, dt.Entrega, df.CT, (select top 1 dt2.Status from ALM_DEFEITOS_Tempos dt2 WITH (NOLOCK) where dt2.Subprojeto = dt.Subprojeto and dt2.Entrega = dt.Entrega and dt2.Defeito = dt.Defeito and convert(datetime, dt2.dt_de, 5) > convert(datetime, dt.dt_de, 5) and dt2.Status <> 'ON_RETEST' --and order by convert(datetime, dt2.dt_de, 5) ) as Status_Posterior from ALM_Defeitos df WITH (NOLOCK) inner join ALM_Defeitos_Tempos dt WITH (NOLOCK) on dt.Subprojeto = df.Subprojeto and dt.Entrega = df.Entrega and dt.Defeito = df.Defeito where df.CT <> '' and df.Status_Atual <> 'CANCELLED' and dt.Status = 'ON_RETEST' ) Aux where Status_Posterior in ('CLOSED','REOPEN') group by Subprojeto, Entrega, CT ) Aux where alm_cts.Subprojeto = Aux.Subprojeto and alm_cts.Entrega = Aux.Entrega and alm_cts.CT = Aux.CT; update alm_cts set alm_cts.Qte_Reteste = 0 where Qte_Reteste is null;
true
c3ee9799fa91562acccb96e238a8dede96dd7017
SQL
utimur/ice_social_network_backend
/src/main/resources/db/migration/V3__post_table.sql
UTF-8
455
3.25
3
[]
no_license
CREATE TABLE post ( id bigint not null auto_increment, user_id bigint not null, creator_id bigint not null, img varchar(255), name varchar(255), surname varchar(255), text varchar(255), creation varchar(255), likes bigint default 0, comments bigint default 0, reposts bigint default 0, primary key (id) ) engine=MyISAM; alter table post add constraint user_fk foreign key (user_id) references usr (id);
true
0c7e2546aafd393ff3827c23fb73e66c47614ab4
SQL
nguyenphong2288/Rocket_VTI
/SQL/Assignment 2/Assignment2.sql
UTF-8
1,168
3.625
4
[]
no_license
-- LECTURE: Creating a Database fresher CREATE DATABASE IF NOT EXISTS fresher; USE fresher; CREATE TABLE Trainee ( Trainee_ID INT AUTO_INCREMENT PRIMARY KEY, Full_Name VARCHAR(50) NOT NULL, Birth_Date DATE NOT NULL, Gender ENUM('male' , 'female', 'unknown'), ET_IQ TINYINT(30), ET_Gmath TINYINT(30), ET_English TINYINT(30), Training_Class CHAR(15) NOT NULL, Evaluation_Notes NVARCHAR(500) ); -- LECTURE: add VTI_Account ALTER TABLE Trainee ADD VTI_Account VARCHAR(200) UNIQUE NOT NULL; --LECTURE : add table food CREATE TABLE food ( ID INT AUTO_INCREMENT PRIMARY KEY , Name VARCHAR(200) NOT NULL , Code CHAR(5) NOT NULL, ModifiedDate DATETIME ); -- LECTURE : add table hanam CREATE TABLE hanam ( ID INT AUTO_INCREMENT PRIMARY KEY , Name VARCHAR(100) NOT NULL, BirtDate DATE NOT NULL, Gender ENUM(0, 1,'NULL'), IsDeletedFlag BIT NOT NULL, -- 0 means active, 1 means deleted );
true
77e1b9644ad4741a638778c0d2430ffa6ac23aaf
SQL
gwax/mtg-dataset
/pipelines/stg_mtg/cards.sql
UTF-8
339
3.453125
3
[]
no_license
/** * Select to construct all cards data. **/ SELECT COALESCE(rc.id, uuid()) AS id, UPPER(sf.set) AS set_code, sf.collector_number AS collector_number, sf.name AS name, sf.id AS scryfall_id FROM src_mtg.raw_recycle_cards AS rc FULL OUTER JOIN src_mtg.raw_scryfall_cards AS sf ON rc.scryfall_id = sf.id
true
a6f7a73b3eb8606fbf8d3039b59cbde388a8dc28
SQL
szidoniaszappanyos/touristapp
/tourist-app-backend/src/main/resources/db/migration/V1.0.17__insert_attractions.sql
UTF-8
3,125
3.375
3
[]
no_license
INSERT INTO locations( id, name, address, details) VALUES (249,'Cetățuia' ,'', '46.773879 23.582829'); INSERT INTO attraction( id, attraction_type_id, location_id, name, details, weekly_schedule_id, cost) VALUES (249, 6, 249, 'Monument of the Heroes of the Nation','The Cross of Cetatuia, designed by Archbishop Virgil Salvanu,' || ' was built between 2000-2002 on Cetatuia Hill in Cluj-Napoca and has a height of almost 23 m and the monument''s weight is 60 tons.',null, 0 ); INSERT INTO locations( id, name, address, details) VALUES (250,' Piața Muzeului ' ,'2', '46.771830 23.587456'); INSERT INTO attraction( id, attraction_type_id, location_id, name, details, weekly_schedule_id, cost) VALUES (250, 6, 250, 'Obeliscul Carolina', '', null, 0); INSERT INTO locations( id, name, address, details) VALUES (251,'Piața Avram Iancu, Cluj-Napoca' ,'nr. 11', '46.772035 23.597012'); INSERT INTO attraction( id, attraction_type_id, location_id, name, details, weekly_schedule_id, cost) VALUES (251, 7, 251, 'Palace of the Orthodox Archdiocese', 'Built in 1887, the palace initially served as the ' || 'headquarters for the Forest Administration. The building was donated to the Romanian Orthodox Church with the ' || 'completion of the Orthodox Cathedral in Avram Iancu Square.', null, 0); INSERT INTO locations( id, name, address, details) VALUES (245,'Strada George Barițiu 4, Cluj-Napoca 400000' ,'', '46.774169 23.588107'); INSERT INTO attraction( id, attraction_type_id, location_id, name, details, weekly_schedule_id, cost) VALUES (245, 7, 245, 'Babos Palace', ' The edifice located on King Ferdinand Street, no. 38, is a prominent representative of the Belle Époque architecture ' || 'in Cluj. The palace is built in a V-like shape and is one of the 4 palaces on the Great Bridge over Somes.', null,0); INSERT INTO locations( id, name, address, details) VALUES (246,' Piața Unirii 30, Cluj-Napoca' ,'', '46.770536 23.590435'); INSERT INTO attraction( id, attraction_type_id, location_id, name, details, weekly_schedule_id, cost) VALUES (246, 7, 246, 'Banffy Palace', 'Probably one of the most famous and easily recognized palaces of Cluj, Banffy Palace is also one of the most' || ' representative Baroque buildings in Cluj, but also from Transylvania.', 11, 0); INSERT INTO locations( id, name, address, details) VALUES (247,' I.C. Brătianu, 22 ' ,'', '46.768954 23.594677'); INSERT INTO attraction( id, attraction_type_id, location_id, name, details, weekly_schedule_id, cost) VALUES (247, 7, 247, ' Béldi Palace', 'Located on I.C. Brătianu, at no. 22, Béldi Palace ' || 'currently houses the French Institute of Cluj.', 1,0); INSERT INTO locations( id, name, address, details) VALUES (248,' Horea 1' ,'', '46.774809 23.587420'); INSERT INTO attraction( id, attraction_type_id, location_id, name, details, weekly_schedule_id, cost) VALUES (248, 7, 248, 'Berde Palace ', ' A prominent representative of the Belle Époque period in Cluj, the Berde Palace was erected in the context of the' || ' modernization of the Mari Street of the city (Nagy utca) at the end of the 19th century.', 13, 0);
true
630cdc682dffb079d0db4b42e8861e066597f8b3
SQL
klahnakoski/datazilla-alerts
/tests/resources/sql/normalized_to_cube.sql
UTF-8
3,936
3.71875
4
[]
no_license
################################################################################ ## This Source Code Form is subject to the terms of the Mozilla Public ## License, v. 2.0. If a copy of the MPL was not distributed with this file, ## You can obtain one at http://mozilla.org/MPL/2.0/. ################################################################################ ## Author: Kyle Lahnakoski (kyle@lahnakoski.com) ################################################################################ use ekyle_perftest_1; DROP index tdad ON test_data_all_dimensions; #TOO SELECTIVE #CREATE UNIQUE INDEX tdad ON test_data_all_dimensions(test_run_id, page_id); CREATE INDEX tdad_test_run_id2 ON test_data_all_dimensions(test_run_id); USE pushlog_hgmozilla_1; ALTER TABLE changesets DROP COLUMN SHORT_revision; ALTER TABLE changesets ADD COLUMN revision VARCHAR(12); CREATE INDEX ch_revision ON changesets(revision); #IT WOULD BE NICE FOR THE APP TO DO THIS, BUT NOT REQUIRED USE pushlog_hgmozilla_1; UPDATE changesets SET revision=substring(node, 1, 12) WHERE revision<>substring(node, 1, 12); use ekyle_perftest_1; DELETE FROM test_data_all_dimensions; INSERT INTO `test_data_all_dimensions` ( `test_run_id`, `product_id`, `operating_system_id`, `test_id`, `page_id`, `date_received`, `revision`, `product`, `branch`, `branch_version`, `operating_system_name`, `operating_system_version`, `processor`, `build_type`, `machine_name`, `pushlog_id`, `push_date`, `test_name`, `page_url`, `mean`, `std`, `h0_rejected`, `p`, `n_replicates`, `fdr`, `trend_mean`, `trend_std`, `test_evaluation` ) SELECT STRAIGHT_JOIN tr.id `test_run_id`, b.product_id `product_id`, o.id `operating_system_id`, tr.test_id `test_id`, tpm.page_id `page_id`, pl.date `date_received`, tr.revision `revision`, p.product `product`, p.branch `branch`, p.version `branch_version`, o.name `operating_system_name`, o.version `operating_system_version`, b.processor `processor`, b.build_type `build_type`, m.name `machine_name`, pl.id `pushlog_id`, pl.date `push_date`, t.name `test_name`, pg.url `page_url`, max(CASE WHEN mv.name='mean' THEN tpm.value ELSE 0 END) `mean`, max(CASE WHEN mv.name='stddev' THEN tpm.value ELSE 0 END) `std`, min(CASE WHEN mv.name='h0_rejected' THEN tpm.value ELSE NULL END) `h0_rejected`, min(CASE WHEN mv.name='p' THEN tpm.value ELSE NULL END) `p`, min(CASE WHEN mv.name='n_replicates' THEN tpm.value ELSE NULL END) `n_replicates`, min(CASE WHEN mv.name='fdr' THEN tpm.value ELSE NULL END) `fdr`, min(CASE WHEN mv.name='trend_mean' THEN tpm.value ELSE NULL END) `trend_mean`, min(CASE WHEN mv.name='trend_stddev' THEN tpm.value ELSE NULL END) `trend_std`, min(CASE WHEN mv.name='`test_evaluation' THEN tpm.value ELSE NULL END) `test_evaluation` FROM `test_run` AS tr LEFT JOIN test_data_all_dimensions AS tdad ON tdad.test_run_id=tr.id #AND tdad.page_id=tpm.page_id LEFT JOIN `test_page_metric` AS tpm ON tpm.test_run_id = tr.id LEFT JOIN `pages` AS pg ON tpm.page_id = pg.id LEFT JOIN `build` AS b ON tr.build_id = b.id LEFT JOIN `product` AS p ON b.product_id = p.id LEFT JOIN `test` AS t ON tr.test_id = t.id LEFT JOIN `metric_value` AS mv ON tpm.metric_value_id = mv.id LEFT JOIN `machine` AS m ON tr.machine_id = m.id LEFT JOIN `operating_system` AS o ON m.operating_system_id = o.id LEFT JOIN pushlog_hgmozilla_1.changesets AS ch ON ch.revision=tr.revision LEFT JOIN pushlog_hgmozilla_1.pushlogs AS pl ON pl.id = ch.pushlog_id LEFT JOIN pushlog_hgmozilla_1.branches AS br ON pl.branch_id = br.id LEFT JOIN pushlog_hgmozilla_1.branch_map AS bm ON br.name = bm.name WHERE tdad.test_run_id IS NULL AND tpm.page_id IS NOT NULL AND tpm.value IS NOT NULL -- AND tr.id>(SELECT max(id)-1000 FROM test_run) # ONLY THE RECENT test_runs GROUP BY tr.id ; select count(1) from test_data_all_dimensions;
true
57b28d3119809217fc901351408046a719098a95
SQL
silence-do-good/stress-test-Postgres-and-MySQL
/dump/high/day17/select1732.sql
UTF-8
177
2.65625
3
[]
no_license
SELECT timeStamp, temperature FROM ThermometerOBSERVATION o WHERE timestamp>'2017-11-16T17:32:00Z' AND timestamp<'2017-11-17T17:32:00Z' AND temperature>=4 AND temperature<=30
true
ec53d667493f10e084e00c5279c15d3be5d13160
SQL
lihansunbai/GraduateStudy
/webMap/php/MyQQ1215/initdb.sql
UTF-8
791
3.078125
3
[]
no_license
drop table qq_user; drop table qq_friend; drop table qq_message; create table qq_user( id serial primary key, username varchar(32) unique not null, realname varchar(32), password varchar(64), regitertime timestamp default now() ); insert into qq_user(username,password,realname) values ('10000',md5('123456'),'laowang'), ('10010',md5('123456'),'wanglao'), ('10011',md5('123456'),'csu'); select * from qq_user; create table qq_friend( id serial primary key, userid integer not null, friendid integer not null ); insert into qq_friend(userid,friendid) values (1,2), (2,1), (1,3), (3,1); select * from qq_friend; create table qq_message( id serial primary key, fromuserid integer, touserid integer, message varchar(1024), sendtime timestamp default now() );
true
da8e02d441f0fe0c51cbfa2afb6963d480b29d07
SQL
MaelsVilen/repo_github
/mySQL/training_DB/lesson4_ex.sql
UTF-8
951
3.640625
4
[]
no_license
-- ii. Написать скрипт, возвращающий список имен (только firstname) -- пользователей без повторений в алфавитном порядке USE vk; SELECT DISTINCT firstname FROM users ORDER BY firstname; -- iii. Написать скрипт, отмечающий несовершеннолетних пользователей как неактивных (поле is_active = false). -- Предварительно добавить такое поле в таблицу profiles со значением по умолчанию = true (или 1) ALTER TABLE profiles ADD is_active BIT DEFAULT 1; UPDATE profiles SET is_active = 0 WHERE (CURDATE() - birthday < 78840); -- iv. Написать скрипт, удаляющий сообщения «из будущего» (дата больше сегодняшней) DELETE FROM messages WHERE (NOW() - created_at < 0);
true
913f89a949be128a2945343e47e10ef4c725383b
SQL
OOP-BPGC/2014-Group-14
/Submissions-3/database/MessManagement.sql
UTF-8
4,989
3.046875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.0.10deb1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Nov 14, 2014 at 09:22 PM -- Server version: 5.5.40-0ubuntu0.14.04.1 -- PHP Version: 5.5.9-1ubuntu4.5 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `MessManagement` -- -- -------------------------------------------------------- -- -- Table structure for table `AlreadyEaten` -- CREATE TABLE IF NOT EXISTS `AlreadyEaten` ( `Id_Number` text NOT NULL, `Eaten` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `Complaint` -- CREATE TABLE IF NOT EXISTS `Complaint` ( `Complaint_Id` int(11) NOT NULL AUTO_INCREMENT, `User_Designation` text NOT NULL, `User_Id` text NOT NULL, `Complaint_Subject` text NOT NULL, `Complaint_Body` text NOT NULL, `Complaint_Status` int(11) NOT NULL, PRIMARY KEY (`Complaint_Id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `HygieneReport` -- CREATE TABLE IF NOT EXISTS `HygieneReport` ( `SR` int(11) NOT NULL AUTO_INCREMENT, `Month` text NOT NULL, `Report` text NOT NULL, `Designation` text NOT NULL, PRIMARY KEY (`SR`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `Inventory` -- CREATE TABLE IF NOT EXISTS `Inventory` ( `SR` int(11) NOT NULL AUTO_INCREMENT, `Item_Name` text NOT NULL, `Item_Price` int(11) NOT NULL, `Item_Quantity` int(11) NOT NULL, PRIMARY KEY (`SR`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `Login` -- CREATE TABLE IF NOT EXISTS `Login` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `User_Id` text NOT NULL, `User_Designation` text NOT NULL, `Password` text NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `Menu` -- CREATE TABLE IF NOT EXISTS `Menu` ( `Day` text NOT NULL, `Breakfast` text NOT NULL, `Lunch` text NOT NULL, `Snacks` text NOT NULL, `Dinner` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `NonStudentList` -- CREATE TABLE IF NOT EXISTS `NonStudentList` ( `SR` int(11) NOT NULL AUTO_INCREMENT, `Name` text NOT NULL, `Id_No` text NOT NULL, `Designation` text NOT NULL, `Phone_Number` text NOT NULL, PRIMARY KEY (`SR`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `Problem` -- CREATE TABLE IF NOT EXISTS `Problem` ( `Problem_Id` int(11) NOT NULL AUTO_INCREMENT, `User_Designation` text NOT NULL, `User_Id` text NOT NULL, `Problem_Subject` text NOT NULL, `Problem_Body` text NOT NULL, `Problem_Status` int(11) NOT NULL, PRIMARY KEY (`Problem_Id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `StudentLeave` -- CREATE TABLE IF NOT EXISTS `StudentLeave` ( `Leave_Id` int(11) NOT NULL AUTO_INCREMENT, `Student_Id` text NOT NULL, `Departure_Date` date NOT NULL, `Departure_Time` time NOT NULL, `Arrival_Date` date NOT NULL, `Arrival_Time` time NOT NULL, PRIMARY KEY (`Leave_Id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `StudentList` -- CREATE TABLE IF NOT EXISTS `StudentList` ( `SR` int(11) NOT NULL AUTO_INCREMENT, `Name` text NOT NULL, `Id_No` text NOT NULL, `Hostel` text NOT NULL, `Current_Mess_Option` int(11) NOT NULL, `Next_Mess_Option` int(11) NOT NULL, PRIMARY KEY (`SR`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `WorkerLeave` -- CREATE TABLE IF NOT EXISTS `WorkerLeave` ( `Leave_Id` int(11) NOT NULL AUTO_INCREMENT, `Worker_Id` text NOT NULL, `Departure_Date` date NOT NULL, `Arrival_Date` date NOT NULL, `Leave_Status` int(11) NOT NULL, PRIMARY KEY (`Leave_Id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
9e066ac2734fc89d26446961b507f4a325f75f46
SQL
silence-do-good/stress-test-Postgres-and-MySQL
/dump/high/day17/select1753.sql
UTF-8
191
2.75
3
[]
no_license
SELECT timeStamp, temperature FROM ThermometerObservation WHERE timestamp>'2017-11-16T17:53:00Z' AND timestamp<'2017-11-17T17:53:00Z' AND SENSOR_ID='8fe559e6_ab25_42d5_b055_73f63ad799b0'
true
4e0a51404d73761084dc8f8bcf26d1a0b381b6cb
SQL
seanmodd/hasura-superapp
/hasura/models/order_product/table.sql
UTF-8
851
3.859375
4
[]
no_license
/* TABLE */ CREATE TABLE "order_product" ( id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, created_at timestamptz DEFAULT now() NOT NULL, updated_at timestamptz DEFAULT now() NOT NULL, order_id int NOT NULL, product_id int NOT NULL, quantity int NOT NULL ); COMMENT ON TABLE "order_product" IS 'A product belonging to a customer order, along with a quantity'; /* FOREIGN KEYS */ ALTER TABLE ONLY public.order_product ADD CONSTRAINT order_id_fkey FOREIGN KEY (order_id) REFERENCES public.order (id); ALTER TABLE ONLY public.order_product ADD CONSTRAINT product_id_fkey FOREIGN KEY (product_id) REFERENCES public.product (id); /* TRIGGERS */ CREATE TRIGGER set_order_product_updated_at BEFORE UPDATE ON public.order_product FOR EACH ROW EXECUTE FUNCTION public.set_current_timestamp_updated_at ();
true
fe958f3946ce2537c25117650acfa32a3c296ce1
SQL
Nigel-Gardner/project2
/schema.sql
UTF-8
664
3.4375
3
[]
no_license
DROP TABLE IF EXISTS users cascade; DROP TABLE IF EXISTS resort cascade; DROP TABLE IF EXISTS visited cascade; CREATE TABLE users( id SERIAL PRIMARY KEY, email VARCHAR (50) NOT NULL, password VARCHAR (250) NOT NULL, firstName VARCHAR (50) NOT NULL, lastName VARCHAR (50) NOT NULL, aboutMe VARCHAR (4000) NOT NULL, skiLevel VARCHAR (50) NOT NULL ); CREATE TABLE resort( id SERIAL PRIMARY KEY, name VARCHAR (50) NOT NULL, city VARCHAR (50) NOT NULL, state VARCHAR (50) NOT NULL ); CREATE TABLE visited( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), resort_id INTEGER REFERENCES resort(id), visit_date VARCHAR (50) NOT NULL );
true
03ae8f81ff5c5d4034dc61bd6687d3b62cb62742
SQL
EddyeBoy27/one-for-all
/desafios/desafio9.sql
UTF-8
975
4.0625
4
[]
no_license
/* Desafio 9 Crie uma procedure chamada albuns_do_artista que recebe como parâmetro o valor da coluna identificadora de um artista e em retorno deve exibir as seguintes quatro colunas: o código identificador do artista, com o apelido "artista_id", o nome do artista, com o apelido "artista", o valor identificador do álbum produzido por aquele artista, com o apelido "album_id" e o nome do álbum, com o apelido "album". Confirme a execução correta da procedure, chamando-a e passando o valor "1" como parâmetro. */ USE SpotifyClone; DELIMITER $$ CREATE PROCEDURE albuns_do_artista(IN id INT) BEGIN SELECT alart.artist_id AS artista_id, art.artist_name AS artista, alart.album_id AS album_id, al.album_name AS album FROM SpotifyClone.album_artists AS alart INNER JOIN SpotifyClone.artists AS art ON alart.artist_id = art.id INNER JOIN SpotifyClone.albuns AS al ON alart.album_id = al.id WHERE art.id = id; END $$ DELIMITER ; CALL albuns_do_artista(1);
true
27d56489066980f860c4e67a06e3c90cfa4ab9e8
SQL
sonepotam/newAthena
/MSFO/CreateScripts/ass_subject_subjgroup.sql
WINDOWS-1251
1,484
3.609375
4
[]
no_license
create table ass_subject_subjgroup ( DT VARCHAR2 ( 10) NOT NULL, SUBJECTGROUP_CODE VARCHAR2(100) NOT NULL, SUBJECT_CODE VARCHAR2(100), REC_STATUS CHAR( 1) NOT NULL, REC_UNLOAD NUMBER(1), REC_PROCESS NUMBER(1), ID_FILE NUMBER(10) ) tablespace MSFO_DATA / comment on column ass_subject_subjgroup.DT is ' ' / comment on column ass_subject_subjgroup.SUBJECTGROUP_CODE is ' ' / comment on column ass_subject_subjgroup.SUBJECT_CODE is ' ' / comment on column ass_subject_subjgroup.REC_STATUS is 'REC_STATUS' / COMMENT ON TABLE ass_subject_subjgroup is ' ' / ALTER TABLE ass_subject_subjgroup ADD CONSTRAINT pk_ass_subject_subjgroup PRIMARY KEY(SUBJECT_CODE) USING INDEX TABLESPACE MSFO_NSI; create bitmap index idx_ass_subj_subjgroup_unl on ass_subject_subjgroup( rec_unload) TABLESPACE MSFO_INDEX; ALTER TABLE ass_subject_subjgroup ADD CONSTRAINT fk_ass_subj_subjgroup_id_file FOREIGN KEY(id_file) REFERENCES bp_fct_files(ID_FILE) / ALTER TABLE ass_subject_subjgroup ADD CONSTRAINT fk_ass_subj_subjgroup_sg_code FOREIGN KEY(subjectgroup_code) REFERENCES det_subjectgroup(code) / ALTER TABLE ass_subject_subjgroup ADD CONSTRAINT fk_ass_subj_subjgroup_subjcode FOREIGN KEY(subject_code) REFERENCES det_subject(code_subject) /
true
14f4ecc9b71c88aa91944b71c2a3c4166adddcad
SQL
mldbai/mldb
/drafts/rec/btr/query_users.sql
UTF-8
203
3.609375
4
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SELECT u.uid, SUBSTRING_INDEX(u.email, '@', -1) as email, ui.gender FROM users as u LEFT JOIN users_info as ui ON ui.uid = u.uid WHERE ui.country = 'CA' -- ORDER BY uid DESC -- LIMIT 10000
true
06ed20f80e3538d66c8dcf26a2d647428c121634
SQL
karrollinaaa/app_php
/baza/baza.sql
UTF-8
794
3.4375
3
[]
no_license
DROP TABLE IF EXISTS menu; CREATE TABLE menu ( id INTEGER PRIMARY KEY AUTOINCREMENT, tytul VARCHAR, plik VARCHAR, pozycja INTEGER ); INSERT INTO menu VALUES (NULL, 'Strona główna', 'glowna.html', 1); INSERT INTO menu VALUES (NULL, 'Wiadomości', 'wiadomosci.html', 2); INSERT INTO menu VALUES (NULL, 'Zarejestruj', 'userform.html', 3); INSERT INTO menu VALUES (NULL, 'Zaloguj się', 'userlogin.html', 4); DROP TABLE IF EXISTS users; CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, login CHAR(20), haslo CHAR(40), email VARCHAR(50), data DATE DEFAULT CERRENT_TIMESTAMP ); DROP TABLE IF EXISTS posty; CREATE TABLE posty ( id INTEGER PRIMARY KEY AUTOINCREMENT, wiadomosc VARCHAR, id_user INTEGER, FOREIGN KEY (id_user) REFERENCES user(id) );
true
3bc4857846d30425a637d3b0675e3b7e3aec4bfe
SQL
tkdonut/shrapnel_cc_project1
/db/shrapnel.sql
UTF-8
562
3.234375
3
[]
no_license
DROP TABLE budgets; DROP TABLE transactions; DROP TABLE vendors; DROP TABLE tags; CREATE TABLE tags ( id SERIAL8 PRIMARY KEY, name VARCHAR(255) ); CREATE TABLE budgets ( id SERIAL8 PRIMARY KEY, tag_id INT8 references tags(id) ON DELETE CASCADE, maxspend VARCHAR(255) ); CREATE TABLE vendors ( id SERIAL8 PRIMARY KEY, name VARCHAR(255) ); CREATE TABLE transactions ( id SERIAL8 PRIMARY KEY, amount DECIMAL, tag_id INT8 references tags(id) ON DELETE CASCADE, vendor_id INT8 references vendors(id) ON DELETE CASCADE, time TIMESTAMP );
true
1d64e81116ba371d90200a9fba64d40ba2c2fcf7
SQL
Aadward/Examples
/spring-boot-jdbc-demo/src/main/resources/sql/schema.sql
UTF-8
263
2.546875
3
[]
no_license
DROP TABLE IF EXISTS `db_tags`; CREATE TABLE IF NOT EXISTS `db_tags` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `tag_name` varchar(100) NOT NULL, `versions` bigint(20) unsigned NOT NULL, `create_time` datetime NOT NULL, PRIMARY KEY (`id`), );
true
714f8294c9028d4eb88698cc7c820f40407cd7ed
SQL
mugilpro/interview-prep
/src/main/resources/sql/Join.sql
UTF-8
1,341
3.296875
3
[]
no_license
Students ID NAME 1 Samantha 2 Julia 3 Britney 4 Kristeen 5 Dyana 6 Jenny 7 Christene 8 Meera 9 Priya 10 Priyanka 11 Paige 12 Jane 13 Belvet 14 Scarlet 15 Salma 16 Amanda 17 Maria 18 Stuart 19 Aamina 20 Amina Friends ID FRIEND_ID 1 14 2 15 3 18 4 19 5 20 6 5 7 6 8 7 9 8 10 1 11 2 12 3 13 4 14 9 15 10 16 11 17 12 18 13 19 16 20 17 Packages ID SALARY 1 15.5 2 15.6 3 16.7 4 18.8 5 31.5 6 45 7 47 8 46 9 39 10 11.1 11 12.1 12 13.1 13 14.1 14 15.1 15 17.1 16 21.1 17 31.1 18 13.15 19 33.33 20 22.16 select s.name from Students s, Friends f, Packages fp, Packages op where s.id = f.id and f.friend_id = fp.id and s.id = op.id and fp.salary > op.salary order by fp.salary; Stuart Priyanka Paige Jane Julia Belvet Amina Kristeen Scarlet Priya Meera
true
9bf22dd9c41df37feddf67abfb9f93e3f914cdfc
SQL
BowenLiu92/Leetcode_SQL
/Q9.sql
UTF-8
253
3.40625
3
[]
no_license
WITH cte AS (SELECT customerid, date, action, row_number() OVER(PARTITION BY customerid ORDER BY Date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS ao FROM "13".transaction t) SELECT customerid, date, action FROM cte WHERE ao = 1 ;
true
f85ffe7ac58bd0ab62d67408a094782d668bcfeb
SQL
thangdinh1607/C1220G2_Dinh-Van-Thang_module3
/b2/BT_determined_key.sql
UTF-8
1,197
3.9375
4
[]
no_license
create database if not exists customer_manager; use customer_manager; create table customers( customer_number int primary key, fullname varchar (50) not null, address varchar(50)not null, email varchar(50), phone int(9) unique ); insert into customers(customer_number,fullname,address,email,phone) value (1,'thangdinh','Đà nẵng','abc@gmail.com','0914123456'), (2,'gau gau','Đà nẵng','abc1@gmail.com','0914123457'); create table accounts( id_account int primary key, type_account varchar(50) not null, openday date, extra_money double not null, id_customer int, foreign key(id_customer)references customers(customer_number) ); insert into accounts(id_account,type_account,openday,extra_money,id_customer) value (3,'vip','2021-12-12',121.121,1), (4,'normal','2021-12-03',121.444,2); create table transactions( id_transaction int primary key, money double not null, time_of_transaction datetime, `description` varchar(100), id_account int , foreign key (id_account) references accounts(id_account) ); insert into transactions(id_transaction,money,time_of_transaction,`description`,id_account) value (5,5.555,'2020-11-22 11:11:11','đóng học phí ',3), (6,5.777,'2020-11-22 12:12:12','đóng học phí ',4);
true
cc207136abb6e587d138bdb7da81a6cce80174cd
SQL
KalinD/Applied-Programming-Course
/06.База данни/Подготовка за изпита/query01/query01.sql
UTF-8
1,332
4.6875
5
[]
no_license
#Problem 1 SELECT * FROM users ORDER BY id; #Problem 2 SELECT * FROM repositories_contributors AS rc WHERE rc.contributor_id = rc.repository_id ORDER BY rc.contributor_id; #Problem 3 SELECT i.id, CONCAT(u.username, ' : ', i.title) AS `issue_assignee` FROM issues AS i JOIN users AS u ON i.assignee_id = u.id ORDER BY i.id DESC; #Problem 4 SELECT f.id, f.name, CONCAT(f.size, 'KB') AS `size` FROM files AS f WHERE NOT EXISTS (SELECT p.parent_id FROM files AS p WHERE p.parent_id = f.id) ORDER BY f.id; SELECT f.id, f.name, CONCAT(f.size, 'KB') AS `size` FROM files AS f WHERE f.id NOT IN (SELECT DISTINCT p.parent_id FROM files AS p WHERE p.parent_id IS NOT NULL) ORDER BY f.id; #Problem 5 SELECT r.id, r.name, COUNT(*) AS `issues` FROM repositories AS r JOIN issues AS i ON r.id = i.repository_id GROUP BY r.id, r.name ORDER BY COUNT(*) DESC LIMIT 5; #Problem 6 SELECT r.id, r.name, (SELECT COUNT(*) FROM commits AS c WHERE c.repository_id = r.id) AS `commits`, (SELECT COUNT(*) FROM repositories_contributors AS rc WHERE rc.repository_id = r.id) AS `contributors` FROM repositories AS r ORDER BY contributors DESC, r.id LIMIT 1; #Problem 7 SELECT r.id, r.name, COUNT(DISTINCT c.contributor_id) AS `users` FROM repositories AS r LEFT JOIN commits AS c ON r.id = c.repository_id GROUP BY r.id ORDER BY users DESC, r.id;
true
d041f59ba05afe871b87ee4d31363cd479914db9
SQL
cityzen12/SQL-Basic
/SQLQuery1.sql
UTF-8
3,277
4.5625
5
[]
no_license
--1 SELECT student.姓名,score.课程编号 FROM student,score WHERE student.学号=score.学号; --2 SELECT student.姓名,course.课程名称,score.成绩 FROM student,course,score WHERE student.学号=score.学号 AND score.课程编号=course.课程编号; --3 SELECT student.姓名,course.课程名称,score.成绩 FROM student,course LEFT OUTER JOIN score ON(score.课程编号=course.课程编号) --4 SELECT distinct student.姓名,course.课程名称 FROM student,course,score WHERE score.学号=student.学号 AND course.课程名称='管理学' --5 SELECT 学号 FROM score WHERE score.课程编号=04010101 INTERSECT SELECT 学号 FROM score WHERE score.课程编号=04010103 --6 SELECT 学号 FROM score WHERE score.课程编号=04010101 EXCEPT SELECT 学号 FROM score WHERE score.课程编号=04010103 --7 SELECT student.姓名,student.入学成绩 FROM student WHERE student.入学成绩>=(SELECT AVG(student.入学成绩) FROM student) --8 SELECT DISTINCT student.学号,score.课程编号 FROM student, score WHERE (student.学号=score.学号 AND score.课程编号=04010101) SELECT student.学号,党员否 FROM student WHERE student.党员否=1 --9 SELECT student.姓名 FROM student WHERE student.性别='女' AND student.入学成绩> (SELECT MAX(student.入学成绩) FROM student WHERE student.性别='男') --10 SELECT student.姓名 FROM student WHERE student.性别='男' AND student.入学成绩> any(SELECT student.入学成绩 FROM student WHERE student.性别='女') --11 SELECT course.课程名称,先修课 FROM course WHERE course.先修课 IS NOT NULL --12 SELECT score.课程编号 FROM score WHERE score.学号=2015094002 INTERSECT SELECT score.课程编号 FROM score WHERE score.学号=2015094001 --13 SELECT DISTINCT student.姓名 FROM student,score WHERE score.课程编号 = ANY( select score.课程编号 from score where score.学号=2015094001) EXCEPT SELECT student.姓名 FROM student WHERE student.学号=2015094001 --14. SELECT DISTINCT student.姓名 FROM student,score WHERE score.学号=student.学号 AND score.课程编号>=ALL( SELECT DISTINCT score.课程编号 FROM score ) --15 SELECT DISTINCT student.姓名 FROM student,score WHERE student.学号=score.学号 AND score.课程编号>ANY( SELECT DISTINCT score.课程编号 FROM student, score WHERE score.学号=2015094003) EXCEPT SELECT student.姓名 FROM student WHERE student.学号=2015094003 --16 SELECT COALESCE(student.性别,'合计') 性别,COUNT(student.性别) 人数 FROM student GROUP BY student.性别 WITH ROLLUP --17 SELECT score.课程编号, COUNT(case when score.成绩>80 then 1 end) as 良好以上, count(case WHEN score.成绩<=80 then 1 end) as 良好以下, count(score.课程编号) 合计 from score GROUP by score.课程编号 /*SELECT CASE WHEN score.成绩>80 THEN '良好以上' WHEN score.成绩<=80 THEN '良好以下' END AS 分段 FROM score WHERE score.成绩 IS NOT NULL SELECT count(score.成绩) FROM score GROUP BY CASE WHEN score.成绩>80 THEN '良好以上' WHEN score.成绩<=80 THEN '良好以下' END*/
true
64f18c132fd5a094b3fc5fff5a768a580f8ab1b2
SQL
cocosip/WeChatFramework
/framework/src/WeChat.Framework.MySql/Scripts/WeChatFramework.sql
UTF-8
647
2.5625
3
[]
no_license
CREATE TABLE IF NOT EXISTS `SdkTickets` ( `AppId` varchar(50) PRIMARY KEY NOT NULL COMMENT '应用AppId', `Ticket` varchar(128) NOT NULL COMMENT 'Ticket', `TicketType` varchar(30) NOT NULL COMMENT 'Ticket类型', `ExpiredIn` int NOT NULL COMMENT '有效期', `LastModifiedTime` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间' ); CREATE TABLE `AccessTokens` IF NOT EXISTS ( `AppId` varchar(50) PRIMARY KEY NOT NULL COMMENT '应用AppId', `Token` text NOT NULL COMMENT 'Token', `ExpiredIn` int NOT NULL COMMENT '有效期', `LastModifiedTime` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间' );
true
fbd9b6a3b0a4142a5ef1199acbe273a297029586
SQL
ichenkaihua/bootshiro
/usthe.sql
UTF-8
17,145
3.34375
3
[ "MIT" ]
permissive
/* Navicat Premium Data Transfer Source Server : local-docker-mysql Source Server Type : MySQL Source Server Version : 50720 Source Host : localhost:12345 Source Schema : usthe Target Server Type : MySQL Target Server Version : 50720 File Encoding : 65001 Date: 12/04/2018 14:36:56 */ DROP DATABASE IF EXISTS usthe; CREATE DATABASE usthe DEFAULT CHARACTER SET utf8; USE usthe; SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for auth_resource -- ---------------------------- DROP TABLE IF EXISTS `auth_resource`; CREATE TABLE `auth_resource` ( `ID` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '资源ID', `CODE` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '资源名称', `NAME` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '资源描述', `PARENT_ID` int(11) NULL DEFAULT NULL COMMENT '父资源编码->菜单', `URI` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '访问地址URL', `TYPE` smallint(4) NULL DEFAULT NULL COMMENT '类型 1:菜单menu 2:资源element(rest-api) 3:资源分类', `METHOD` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '访问方式 GET POST PUT DELETE PATCH', `ICON` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图标', `STATUS` smallint(4) NULL DEFAULT 1 COMMENT '状态 1:正常、9:禁用', `CREATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `UPDATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`ID`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 145 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '资源信息表(菜单,资源)' ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of auth_resource -- ---------------------------- INSERT INTO `auth_resource` VALUES (101, 'ACCOUNT_LOGIN', '用户登录', 103, '/account/login', 2, 'POST', NULL, 1, NULL, NULL); INSERT INTO `auth_resource` VALUES (103, 'GROUP_ACCOUNT', '账户系列', 110, '', 3, 'POST', NULL, 1, NULL, NULL); INSERT INTO `auth_resource` VALUES (104, 'USER_MAGE', '用户管理', -1, '/index/user', 1, 'POST', 'fa fa-user', 1, NULL, NULL); INSERT INTO `auth_resource` VALUES (106, 'RESOURCE_MAGE', '资源配置', -1, '', 1, 'POST', 'fa fa-pie-chart', 1, NULL, NULL); INSERT INTO `auth_resource` VALUES (107, 'MENU_MANAGE', '菜单管理', 106, '/index/menu', 1, 'POST', 'fa fa-th', 1, NULL, NULL); INSERT INTO `auth_resource` VALUES (109, 'API_MANAGE', 'API管理', 106, '/index/api', 1, NULL, 'fa fa-share', 1, '2018-04-07 09:40:24', '2018-04-07 09:40:24'); INSERT INTO `auth_resource` VALUES (110, 'CATEGORY_GROUP', '分类集合(API类别请放入此集合)', -1, NULL, 3, NULL, NULL, 1, '2018-04-07 14:27:58', '2018-04-07 14:27:58'); INSERT INTO `auth_resource` VALUES (112, 'ACCOUNT_REGISTER', '用户注册', 103, '/account/register', 2, 'POST', NULL, 1, '2018-04-07 16:21:45', '2018-04-07 16:21:45'); INSERT INTO `auth_resource` VALUES (115, 'GROUP_USER', '用户系列', 110, '', 3, 'GET', NULL, 1, '2018-04-07 16:31:01', '2018-04-07 16:31:01'); INSERT INTO `auth_resource` VALUES (117, 'ROLE_MANAGE', '角色管理', 106, '/index/role', 1, NULL, 'fa fa-adjust', 1, '2018-04-08 05:36:31', '2018-04-08 05:36:31'); INSERT INTO `auth_resource` VALUES (118, 'GROUP_RESOURCE', '资源系列', 110, NULL, 3, NULL, NULL, 1, '2018-04-09 02:29:14', '2018-04-09 02:29:14'); INSERT INTO `auth_resource` VALUES (119, 'USER_ROLE_APPID', '获取对应用户角色', 115, '/user/role', 2, 'GET', NULL, 1, '2018-04-12 03:07:22', '2018-04-12 03:07:22'); INSERT INTO `auth_resource` VALUES (120, 'USER_LIST', '获取用户列表', 115, '/user/list', 2, 'GET', NULL, 1, '2018-04-12 03:08:30', '2018-04-12 03:08:30'); INSERT INTO `auth_resource` VALUES (121, 'USER_AUTHORITY_ROLE', '给用户授权添加角色', 115, '/user/authority/role', 2, 'POST', NULL, 1, '2018-04-12 03:15:56', '2018-04-12 03:15:56'); INSERT INTO `auth_resource` VALUES (122, 'USER_AUTHORITY_ROLE', '删除已经授权的用户角色', 115, '/user/authority/role', 2, 'DELETE', NULL, 1, '2018-04-12 03:29:03', '2018-04-12 03:29:03'); INSERT INTO `auth_resource` VALUES (123, 'RESOURCE_AUTORITYMENU', '获取用户被授权菜单', 118, '/resource/authorityMenu', 2, 'GET', NULL, 1, '2018-04-12 05:30:03', '2018-04-12 05:30:03'); INSERT INTO `auth_resource` VALUES (124, 'RESOURCE_MENUS', '获取全部菜单列', 118, '/resource/menus', 2, 'GET', NULL, 1, '2018-04-12 05:42:46', '2018-04-12 05:42:46'); INSERT INTO `auth_resource` VALUES (125, 'RESOURCE_MENU', '增加菜单', 118, '/resource/menu', 2, 'POST', NULL, 1, '2018-04-12 06:15:39', '2018-04-12 06:15:39'); INSERT INTO `auth_resource` VALUES (126, 'RESOURCE_MENU', '修改菜单', 118, '/resource/menu', 2, 'PUT', NULL, 1, '2018-04-12 06:16:35', '2018-04-12 06:16:35'); INSERT INTO `auth_resource` VALUES (127, 'RESOURCE_MENU', '删除菜单', 118, '/resource/menu', 2, 'DELETE', NULL, 1, '2018-04-12 06:17:18', '2018-04-12 06:17:18'); INSERT INTO `auth_resource` VALUES (128, 'RESOURCE_API', '获取API list', 118, '/resource/api', 2, 'GET', NULL, 1, '2018-04-12 06:18:02', '2018-04-12 06:18:02'); INSERT INTO `auth_resource` VALUES (129, 'RESOURCE_API', '增加API', 118, '/resource/api', 2, 'POST', NULL, 1, '2018-04-12 06:18:42', '2018-04-12 06:18:42'); INSERT INTO `auth_resource` VALUES (130, 'RESOURCE_API', '修改API', 118, '/resource/api', 2, 'PUT', NULL, 1, '2018-04-12 06:19:32', '2018-04-12 06:19:32'); INSERT INTO `auth_resource` VALUES (131, 'RESOURCE_API', '删除API', 118, '/resource/api', 2, 'DELETE', NULL, 1, '2018-04-12 06:20:03', '2018-04-12 06:20:03'); INSERT INTO `auth_resource` VALUES (132, 'GROUP_ROLE', '角色系列', 110, NULL, 3, NULL, NULL, 1, '2018-04-12 06:22:02', '2018-04-12 06:22:02'); INSERT INTO `auth_resource` VALUES (133, 'ROLE_USER', '获取角色关联用户列表', 132, '/role/user', 2, 'GET', NULL, 1, '2018-04-12 06:22:59', '2018-04-12 06:22:59'); INSERT INTO `auth_resource` VALUES (134, 'ROLE_USER', '获取角色未关联用户列表', 132, '/role/user/-/', 2, 'GET', NULL, 1, '2018-04-12 06:24:09', '2018-04-12 06:24:09'); INSERT INTO `auth_resource` VALUES (135, 'ROLE_API', '获取角色关联API资源', 132, '/role/api', 2, 'GET', NULL, 1, '2018-04-12 06:25:32', '2018-04-12 06:25:32'); INSERT INTO `auth_resource` VALUES (136, 'ROLE_API', '获取角色未关联API资源', 132, '/role/api/-/', 2, 'GET', NULL, 1, '2018-04-12 06:26:12', '2018-04-12 06:26:12'); INSERT INTO `auth_resource` VALUES (137, 'ROLE_MENU', '获取角色关联菜单资源', 132, 'role/menu', 2, 'GET', NULL, 1, '2018-04-12 06:27:20', '2018-04-12 06:27:20'); INSERT INTO `auth_resource` VALUES (138, 'ROLE_MENU', '获取角色未关联菜单资源', 132, '/role/menu/-/', 2, 'GET', NULL, 1, '2018-04-12 06:27:56', '2018-04-12 06:27:56'); INSERT INTO `auth_resource` VALUES (139, 'ROLE_AUTHORITY_RESOURCE', '授权资源给角色', 132, '/role/authority/resource', 2, 'POST', NULL, 1, '2018-04-12 06:29:45', '2018-04-12 06:29:45'); INSERT INTO `auth_resource` VALUES (140, 'ROLE_AUTHORITY_RESOURCE', '删除角色的授权资源', 132, '/role/authority/resource', 2, 'DELETE', NULL, 1, '2018-04-12 06:31:12', '2018-04-12 06:31:12'); INSERT INTO `auth_resource` VALUES (141, 'ROLE', '获取角色LIST', 132, 'role', 2, 'GET', NULL, 1, '2018-04-12 06:32:34', '2018-04-12 06:32:34'); INSERT INTO `auth_resource` VALUES (142, 'ROLE', '添加角色', 132, 'role', 2, 'POST', NULL, 1, '2018-04-12 06:33:25', '2018-04-12 06:33:25'); INSERT INTO `auth_resource` VALUES (143, 'USER', '更新角色', 132, 'role', 2, 'PUT', NULL, 1, '2018-04-12 06:34:27', '2018-04-12 06:34:27'); INSERT INTO `auth_resource` VALUES (144, 'ROLE', '删除角色', 132, 'role', 2, 'DELETE', NULL, 1, '2018-04-12 06:35:15', '2018-04-12 06:35:15'); -- ---------------------------- -- Table structure for auth_role -- ---------------------------- DROP TABLE IF EXISTS `auth_role`; CREATE TABLE `auth_role` ( `ID` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '角色ID', `CODE` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '角色编码', `NAME` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '角色名称', `STATUS` smallint(4) NULL DEFAULT 1 COMMENT '状态 1:正常、9:禁用', `CREATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `UPDATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`ID`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 105 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '角色信息表' ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of auth_role -- ---------------------------- INSERT INTO `auth_role` VALUES (100, 'role_admin', '管理员角色', 1, NULL, NULL); INSERT INTO `auth_role` VALUES (102, 'role_user', '用户角色', 1, NULL, NULL); INSERT INTO `auth_role` VALUES (103, 'role_guest', '访客角色', 1, NULL, NULL); INSERT INTO `auth_role` VALUES (104, 'role_anon', '非角色', 1, NULL, NULL); -- ---------------------------- -- Table structure for auth_role_resource -- ---------------------------- DROP TABLE IF EXISTS `auth_role_resource`; CREATE TABLE `auth_role_resource` ( `ID` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', `ROLE_ID` int(11) NOT NULL COMMENT '角色ID', `RESOURCE_ID` int(11) NOT NULL COMMENT '资源ID', `CREATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `UPDATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`ID`) USING BTREE, UNIQUE INDEX `ROLE_ID`(`ROLE_ID`, `RESOURCE_ID`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 43 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '资源角色关联表' ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of auth_role_resource -- ---------------------------- INSERT INTO `auth_role_resource` VALUES (10, 103, 105, '2018-04-01 12:50:19', '2018-04-01 12:50:19'); INSERT INTO `auth_role_resource` VALUES (21, 102, 102, '2018-04-09 21:09:09', '2018-04-09 21:09:09'); INSERT INTO `auth_role_resource` VALUES (23, 103, 101, '2018-04-09 21:51:39', '2018-04-09 21:51:39'); INSERT INTO `auth_role_resource` VALUES (24, 103, 102, '2018-04-09 21:51:43', '2018-04-09 21:51:43'); INSERT INTO `auth_role_resource` VALUES (25, 103, 103, '2018-04-09 21:51:46', '2018-04-09 21:51:46'); INSERT INTO `auth_role_resource` VALUES (26, 103, 112, '2018-04-09 21:51:49', '2018-04-09 21:51:49'); INSERT INTO `auth_role_resource` VALUES (27, 101, 112, '2018-04-09 22:21:02', '2018-04-09 22:21:02'); INSERT INTO `auth_role_resource` VALUES (28, 101, 103, '2018-04-09 22:21:06', '2018-04-09 22:21:06'); INSERT INTO `auth_role_resource` VALUES (29, 100, 102, '2018-04-09 22:25:09', '2018-04-09 22:25:09'); INSERT INTO `auth_role_resource` VALUES (30, 101, 101, '2018-04-09 22:39:28', '2018-04-09 22:39:28'); INSERT INTO `auth_role_resource` VALUES (31, 103, 100, '2018-04-09 22:45:00', '2018-04-09 22:45:00'); INSERT INTO `auth_role_resource` VALUES (32, 103, 104, '2018-04-09 22:46:26', '2018-04-09 22:46:26'); INSERT INTO `auth_role_resource` VALUES (33, 103, 106, '2018-04-09 22:46:28', '2018-04-09 22:46:28'); INSERT INTO `auth_role_resource` VALUES (34, 103, 107, '2018-04-09 22:46:31', '2018-04-09 22:46:31'); INSERT INTO `auth_role_resource` VALUES (35, 103, 109, '2018-04-09 22:46:34', '2018-04-09 22:46:34'); INSERT INTO `auth_role_resource` VALUES (36, 103, 116, '2018-04-09 22:46:37', '2018-04-09 22:46:37'); INSERT INTO `auth_role_resource` VALUES (37, 103, 117, '2018-04-09 22:46:43', '2018-04-09 22:46:43'); INSERT INTO `auth_role_resource` VALUES (38, 104, 101, '2018-04-09 22:49:46', '2018-04-09 22:49:46'); INSERT INTO `auth_role_resource` VALUES (39, 104, 102, '2018-04-09 22:49:52', '2018-04-09 22:49:52'); INSERT INTO `auth_role_resource` VALUES (40, 104, 103, '2018-04-09 22:49:55', '2018-04-09 22:49:55'); INSERT INTO `auth_role_resource` VALUES (41, 100, 103, '2018-04-09 22:51:56', '2018-04-09 22:51:56'); INSERT INTO `auth_role_resource` VALUES (42, 102, 101, '2018-04-11 09:35:37', '2018-04-11 09:35:37'); -- ---------------------------- -- Table structure for auth_user -- ---------------------------- DROP TABLE IF EXISTS `auth_user`; CREATE TABLE `auth_user` ( `uid` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'uid,用户账号,主键', `username` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名(nick_name)', `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码(MD5(密码+盐))', `salt` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '盐', `real_name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户真名', `avatar` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '头像', `phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话号码(唯一)', `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮件地址(唯一)', `sex` tinyint(4) NULL DEFAULT NULL COMMENT '性别(1.男 2.女)', `status` tinyint(4) NULL DEFAULT NULL COMMENT '账户状态(1.正常 2.锁定 3.删除 4.非法)', `CREATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `UPDATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', `CREATE_WHERE` tinyint(4) NULL DEFAULT NULL COMMENT '创建来源(1.web 2.android 3.ios 4.win 5.macos 6.ubuntu)', PRIMARY KEY (`uid`) USING BTREE, UNIQUE INDEX `phone`(`phone`) USING BTREE, UNIQUE INDEX `email`(`email`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户信息表' ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of auth_user -- ---------------------------- INSERT INTO `auth_user` VALUES ('2825', 'tm8', '3DEAAE4A62A4593D67FBCD1B5C767781', 'bqgvis', NULL, NULL, NULL, NULL, NULL, 1, '2018-03-20 10:24:48', '2018-03-20 02:24:48', NULL); INSERT INTO `auth_user` VALUES ('tom', 'tom', '57B478F76646272DD3FC12B0ED7E492F', '8fig1z', NULL, NULL, NULL, NULL, NULL, 1, '2018-03-31 18:49:32', '2018-03-31 10:49:54', NULL); -- ---------------------------- -- Table structure for auth_user_role -- ---------------------------- DROP TABLE IF EXISTS `auth_user_role`; CREATE TABLE `auth_user_role` ( `ID` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户角色关联表主键', `USER_ID` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户UID', `ROLE_ID` int(11) NOT NULL COMMENT '角色ID', `CREATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `UPDATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`ID`) USING BTREE, UNIQUE INDEX `USER_ID`(`USER_ID`, `ROLE_ID`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户角色关联表' ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of auth_user_role -- ---------------------------- INSERT INTO `auth_user_role` VALUES (6, 'tom', 103, '2018-04-01 12:19:36', '2018-04-01 12:19:36'); INSERT INTO `auth_user_role` VALUES (15, '282870345', 103, '2018-04-09 22:44:47', '2018-04-09 22:44:47'); INSERT INTO `auth_user_role` VALUES (16, 'tom', 102, '2018-04-11 09:36:25', '2018-04-11 09:36:25'); DROP TABLE IF EXISTS `auth_account_log`; CREATE TABLE `auth_account_log` ( `ID` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户账户操作日志主键', `LOG_NAME` varchar(255) DEFAULT NULL COMMENT '日志名称(login,register,logout)', `USER_ID` VARCHAR(30) DEFAULT NULL COMMENT '用户id', `CREATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `SUCCEED` tinyint(4) NULL DEFAULT NULL COMMENT '是否执行成功(0失败1成功)', `MESSAGE` VARCHAR(255) COMMENT '具体消息', `IP` VARCHAR(255) DEFAULT NULL COMMENT '登录ip', PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COMMENT='登录注册登出记录'; DROP TABLE IF EXISTS `auth_operation_log`; CREATE TABLE `auth_operation_log` ( `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户操作日志主键', `LOG_NAME` varchar(255) DEFAULT NULL COMMENT '日志名称', `USER_ID` varchar(30) DEFAULT NULL COMMENT '用户id', `API` varchar(255) DEFAULT NULL COMMENT 'api名称', `METHOD` varchar(255) COMMENT '方法名称', `CREATE_TIME` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `SUCCEED` tinyint(4) NULL DEFAULT NULL COMMENT '是否执行成功(0失败1成功)', `MESSAGE` varchar(255) COMMENT '具体消息备注', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COMMENT='操作日志'; SET FOREIGN_KEY_CHECKS = 1;
true
a3dc2bada039ff3230e8d1d26f639e5d6bda4aa5
SQL
thebhushanp/spring-sec
/src/main/resources/db/migration/V1.001.005__alter_game_table.sql
UTF-8
142
3.09375
3
[]
no_license
alter table game add column admin_id integer, add constraint fk_admin foreign key (admin_id) references usr (id);
true
29471c345a2cbc56bd9af1e0ce171801707126c8
SQL
RenanFragaio/Movement.org
/base/movement.sql
UTF-8
5,229
3.46875
3
[]
no_license
/*drop database if exists id6802051_movement;*/ create database if not exists id6802051_movement; use id6802051_movement; drop table if exists usuario; create table usuario ( id_usuario int auto_increment, nome varchar(80), email varchar(80), senha varchar(20), data_nasc date, bio varchar(255), foto_perfil varchar(255), capa varchar(255), nivel varchar(30), Primary Key(id_usuario) ); drop table if exists post; create table post ( id_post int auto_increment, id_usuario int, conteudo text, data_hora datetime, curtidas int default 0, Primary Key(id_post) ); drop table if exists midia_post; create table midia_post ( id_post int, id_midia int, Primary Key(id_post,id_midia) ); drop table if exists midia; create table midia ( id_midia int auto_increment, id_usuario int, arquivo varchar(255), /*tipo varchar(255),*/ Primary Key(id_midia) ); drop table if exists amizade; create table amizade ( id_usuario1 int, id_usuario2 int, Primary Key(id_usuario1,id_usuario2) ); drop table if exists curtir; create table curtir ( id_usuario int, id_post int, Primary Key(id_usuario,id_post) ); drop table if exists pagina; create table pagina ( id_pagina int auto_increment, nome varchar(255), foto_perfil varchar(255), descricao varchar(255), capa varchar(255), data_criacao datetime, Primary Key(id_pagina) ); alter table post add( Foreign key(id_usuario) references usuario(id_usuario) on update cascade on delete restrict ); alter table midia add( Foreign Key(id_usuario) references usuario(id_usuario) on update cascade on delete restrict ); alter table midia_post add( Foreign Key(id_post) references post(id_post) on update cascade on delete restrict ); alter table midia_post add( Foreign Key(id_midia) references midia(id_midia) on update cascade on delete restrict ); alter table amizade add( Foreign Key(id_usuario1) references usuario(id_usuario) on update cascade on delete restrict ); alter table amizade add( Foreign Key(id_usuario2) references usuario(id_usuario) on update cascade on delete restrict ); alter table curtir add( Foreign Key(id_usuario) references usuario(id_usuario) on update cascade on delete restrict ); alter table curtir add( Foreign Key(id_post) references post(id_post) on update cascade on delete restrict ); insert into usuario(nome,email,senha,data_nasc,foto_perfil,nivel,capa) values ('Lucas Tejedor','tejedor@email.com','tejedor123','1998-01-20','../usuario/foto/semfoto.jpg','adm','../usuario/capa/apple-mouse-artificial-flowers-blurred-background-1229861.jpg'); insert into usuario(nome,email,senha,data_nasc,foto_perfil,nivel,capa) values ('Renan Fragaio','renan@email.com','123456','1999-01-23','../usuario/foto/semfoto.jpg','basico','../usuario/capa/architecture-background-buildings-218983.jpg'); insert into usuario(nome,email,senha,data_nasc,foto_perfil,nivel) values ('Usuario 1','u1@email.com','123456','1999-04-10','../usuario/foto/semfoto.jpg','basico'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('1','1','Pensando em postar alguma coisa','2019-01-17 08:00:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('2','1','Pensando em postar alguma coisa com uma imagem','2019-01-17 09:00:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('3','2','Pensando em postar alguma coisa','2019-01-18 08:00:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('4','2','Pensando em postar alguma coisa com uma imagem','2019-01-18 09:00:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('5','3','Postagem numero 4','2019-01-18 08:37:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('6','3','Postagem numero 5','2019-01-19 09:55:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('7','3','Postagem numero 6','2019-01-20 10:02:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('8','3','Postagem numero 7','2019-01-21 11:12:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('9','3','Postagem numero 8','2019-01-22 12:46:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('10','3','Postagem numero 9','2019-01-23 13:19:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('11','3','Postagem numero 10','2019-01-24 14:02:00'); insert into post(id_post,id_usuario,conteudo,data_hora) values ('12','3','Postagem numero 11','2019-01-25 15:34:00'); insert into midia(id_midia,id_usuario,arquivo) values ('1','1','../midia/arquivo/lock-solid.png'); insert into midia_post(id_post,id_midia) values ('2','1'); insert into midia_post(id_post,id_midia) values ('4','1'); insert into pagina(id_pagina,nome,foto_perfil,descricao,capa,data_criacao) values ('1','Direita BR','../pagina/foto/semfoto_p.png','Uma página de direita','../pagina/capa/semcapa.png','2019-09-02 8:48:00'); insert into pagina(id_pagina,nome,foto_perfil,descricao,capa,data_criacao) values ('2','Esquerda BR','../pagina/foto/semfoto_p.png','Uma página de esquerda','../pagina/capa/semcapa.png','2019-09-02 9:48:00'); insert into pagina(id_pagina,nome,foto_perfil,descricao,capa,data_criacao) values ('3','Pagina1','../pagina/foto/semfoto_p.png','Uma página de esquerda','../pagina/capa/semcapa.png','2019-09-02 9:48:00');
true
599a91055f3b3ce550bda6c61bc59c5776f70376
SQL
warelab/gramene-ensembl
/maize/sql/clone_stats.sql
UTF-8
484
3.828125
4
[ "MIT", "Apache-2.0" ]
permissive
select count(*) from contig; select clone.status, min(c.size), max(c.size), avg(c.size), count(*) from clone left join (select id, clone_id, end_coord-start_coord+1 as size from contig) c on c.clone_id = clone.id group by clone.status with rollup select status, min(cnt), max(cnt), avg(cnt), sum(cnt) from ( select clone.status, count(*) cnt from clone left join contig on contig.clone_id = clone.id group by clone.id) counts group by status with rollup
true
5a5443768bffd9128d9b56c77d0af7d839879c2f
SQL
Kaique-Henryque/ProjetoMVC2020
/BD/BD.sql
UTF-8
703
2.703125
3
[]
no_license
create database ProjetoMVCD26; use ProjetoMVCD26; create table dt_clienteD26( id_cliente int(11) not null, nome_cliente varchar(45) not null, sobrenome_cliente varchar(45) not null, email_cliente varchar(50) not null, senha_cliente varchar(45) not null, cpf_cliente varchar(11) not null, nome_mae varchar(50)not null, tp_cliente int(1) not null ); drop table dt_clienteD26; drop database ProjetoMVCD26; insert into dt_clienteD26() values(1,'a','a','a','a','1','a',1); select * from dt_clienteD26 where nome_cliente = 'Kaique' && sobrenome_cliente = 'Henryque'; select * from dt_clienteD26 where cpf_cliente = '012' && nome_cliente = 'kaique' && nome_mae = 'Glaucilene';
true
eecd1e213ec3ea881564b1a26b0f7a7361cdb800
SQL
gchq/stroom
/stroom-legacy/stroom-legacy-db-migration/src/main/resources/stroom/legacy/db/migration/V07_00_00_1905__processor_filter.sql
UTF-8
3,955
4.03125
4
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0", "CDDL-1.0", "GPL-1.0-or-later", "LGPL-2.0-or-later", "MPL-1.0", "CC-BY-4.0", "LicenseRef-scancode-public-domain", "EPL-1.0" ]
permissive
-- ------------------------------------------------------------------------ -- Copyright 2020 Crown Copyright -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- ------------------------------------------------------------------------ -- Stop NOTE level warnings about objects (not)? existing SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0; -- -- Create the table -- CREATE TABLE IF NOT EXISTS`processor_filter` ( `id` int NOT NULL AUTO_INCREMENT, `version` int NOT NULL, `create_time_ms` bigint NOT NULL, `create_user` varchar(255) NOT NULL, `update_time_ms` bigint NOT NULL, `update_user` varchar(255) NOT NULL, `uuid` varchar(255) NOT NULL, `fk_processor_id` int NOT NULL, `fk_processor_filter_tracker_id` int NOT NULL, `data` longtext NOT NULL, `priority` int NOT NULL, `reprocess` tinyint NOT NULL DEFAULT '0', `enabled` tinyint NOT NULL DEFAULT '0', `deleted` tinyint NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `uuid` (`uuid`), KEY `processor_filter_fk_processor_id` (`fk_processor_id`), KEY `processor_filter_fk_processor_filter_tracker_id` (`fk_processor_filter_tracker_id`), CONSTRAINT `processor_filter_fk_processor_filter_tracker_id` FOREIGN KEY (`fk_processor_filter_tracker_id`) REFERENCES `processor_filter_tracker` (`id`), CONSTRAINT `processor_filter_fk_processor_id` FOREIGN KEY (`fk_processor_id`) REFERENCES `processor` (`id`) ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci; DROP PROCEDURE IF EXISTS copy_processor_filter; DELIMITER // CREATE PROCEDURE copy_processor_filter () BEGIN IF EXISTS ( SELECT NULL FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = database() AND TABLE_NAME = 'STRM_PROC_FILT') THEN RENAME TABLE STRM_PROC_FILT TO OLD_STRM_PROC_FILT; END IF; -- Check again so it is idempotent IF EXISTS ( SELECT NULL FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = database() AND TABLE_NAME = 'OLD_STRM_PROC_FILT') THEN -- -- Copy data into the table, use ID predicate to make it re-runnable -- INSERT INTO processor_filter ( id, version, create_time_ms, create_user, update_time_ms, update_user, uuid, fk_processor_id, fk_processor_filter_tracker_id, data, priority, enabled) SELECT ID, VER, IFNULL(CRT_MS, 0), IFNULL(CRT_USER, 'UNKNOWN'), IFNULL(UPD_MS, 0), IFNULL(UPD_USER, 'UNKNOWN'), md5(UUID()), FK_STRM_PROC_ID, FK_STRM_PROC_FILT_TRAC_ID, DAT, PRIOR, ENBL FROM OLD_STRM_PROC_FILT WHERE ID > (SELECT COALESCE(MAX(id), 0) FROM processor_filter) ORDER BY ID; -- Work out what to set our auto_increment start value to SELECT CONCAT('ALTER TABLE processor_filter AUTO_INCREMENT = ', COALESCE(MAX(id) + 1, 1)) INTO @alter_table_sql FROM processor_filter; PREPARE alter_table_stmt FROM @alter_table_sql; EXECUTE alter_table_stmt; END IF; END// DELIMITER ; CALL copy_processor_filter(); DROP PROCEDURE copy_processor_filter; SET SQL_NOTES=@OLD_SQL_NOTES; -- vim: set shiftwidth=4 tabstop=4 expandtab:
true
08aee90c78c8a54545ac7ee27b2534a106f3bab7
SQL
SarveshSingh101/Microsoft-SQL-Server-And-TSQL-Course-For-Beginners
/Part 8 - Practical SQL Scenarios/Problem 1.sql
UTF-8
231
2.90625
3
[ "MIT" ]
permissive
SELECT DISTINCT JobTitle FROM HumanResources.Employee WHERE Gender = 'M' EXCEPT SELECT DISTINCT JobTitle FROM HumanResources.Employee WHERE Gender = 'F' SELECT * FROM HumanResources.Employee WHERE JobTitle = 'Marketing Manager'
true
069df0593a745e234786995bd11cf5b997212d12
SQL
FilipeMSoares/GameQualityAssessment
/data/desafio/raw_data/round_number_valid_filter.sql
UTF-8
725
3.859375
4
[]
no_license
 select g.tournamentcode, g.seriescode, g.groupcode from game as g, (select tournamentcode, seriescode, max(roundorder) as round_max from gameround group by tournamentcode, seriescode ) as rmax, (select tournamentcode, seriescode, groupcode, max(roundorder) as r_order from gameround group by tournamentcode, seriescode, groupcode ) as rgroup where g.tournamentcode = rmax.tournamentcode and g.tournamentcode = rgroup.tournamentcode and g.seriescode = rmax.seriescode and g.seriescode = rgroup.seriescode and g.groupcode = rgroup.groupcode and rmax.round_max = rgroup.r_order --apenas jogos com o mesmo número de rodadas que o máximo da série order by tournamentcode, seriescode;
true