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
5062878d13dad74b8c595b876861a50113835f7b
SQL
uvalib/apollo
/backend/db/queries.sql
UTF-8
1,262
3.5625
4
[]
no_license
-- get tree SELECT n.id, n.parent_id, n.sequence, n.pid, n.value, n.created_at, n.updated_at, nt.pid, nt.name, nt.controlled_vocab FROM nodes n INNER JOIN node_types nt ON nt.id = n.node_type_id WHERE deleted=0 and current=1 and (n.id=1 or ancestry REGEXP '(^.*/|^)1($|/.*)') order by n.id asc; -- get CHILDREN SELECT n.id, n.parent_id, n.ancestry, n.sequence, n.pid, n.value, n.created_at, n.updated_at, nt.pid, nt.name, nt.controlled_vocab FROM nodes n INNER JOIN node_types nt ON nt.id = n.node_type_id WHERE deleted=0 and current=1 and (n.id=11 or ancestry REGEXP '(^.*/|^)11$' and n.value <> "") order by n.id asc; -- get parent collection SELECT n.id, n.parent_id, n.sequence, n.pid, n.value, n.created_at, n.updated_at, nt.pid, nt.name, nt.controlled_vocab FROM nodes n INNER JOIN node_types nt ON nt.id = n.node_type_id WHERE deleted=0 and current=1 and (n.id=1052 or ancestry REGEXP '^1052$' and n.value <> ""); select * from nodes where id=411 or parent_id=411 or ancestry like "%/411" or ancestry like "%/411/%"; select * from nodes where id=442 or parent_id=442 or ancestry like "%/442" or ancestry like "%/442/%"; select * from nodes where id=582 or parent_id=582 or ancestry like "%/582" or ancestry like "%/582/%";
true
cbf9cd8ef175ed93a8e25cb9ac5bca489036cafd
SQL
farazyarkhan/Data-Analysis-Portfolio
/SQL/Data Cleaning In SQL (Nashville Housing Dataset).sql
UTF-8
2,526
4.25
4
[]
no_license
--Dataset That We Will Be Working On. select * from HousingData --Removing Timestamp from SaleDate Column. alter table HousingData add CleanSaleDate date; update HousingData set CleanSaleDate = CONVERT(Date, SaleDate) alter table HousingData drop column SaleDate; sp_rename 'HousingData.CleanSaleDate', 'SaleDate', 'COLUMN'; select SaleDate from HousingData --Handling Null Values In PropertyAddress Column. select PropertyAddress from HousingData where PropertyAddress is null update a set PropertyAddress = isnull(a.PropertyAddress, b.PropertyAddress) from HousingData a join HousingData b on a.ParcelID = b.ParcelID and a.[UniqueID ] <> b.[UniqueID ] where a.PropertyAddress is null --Spliting PropertyAddress Column into Two Different Columns of SplitPropAddress and SplitPropCity. alter table HousingData add SplitPropAddress nvarchar(250); update HousingData set SplitPropAddress = substring(PropertyAddress, 1, charindex(',', PropertyAddress) -1 ) select SplitPropAddress from HousingData alter table HousingData add SplitPropCitys nvarchar(250); update HousingData set SplitPropCitys = substring (PropertyAddress, charindex(',', PropertyAddress) + 1 , len(PropertyAddress)) select SplitPropCitys from HousingData --Splitting OwnerAddress Column into Three Different Columns of SplitOwnAddress, SplitOwnCity, SplitOwnState. alter table HousingData add SplitOwnAddress nvarchar(250); update HousingData set SplitOwnAddress = parsename(replace(OwnerAddress, ',', '.'), 3) select SplitOwnAddress from HousingData alter table HousingData add SplitOwnCity nvarchar(250); update HousingData set SplitOwnCity = parsename(replace(OwnerAddress, ',', '.'), 2) select SplitOwnCity from HousingData alter table HousingData add SplitOwnstate nvarchar(250); update HousingData set SplitOwnState= parsename(replace(OwnerAddress, ',', '.'), 1) select SplitOwnState from HousingData --Handling Redundancy in SoldAsVaccant Column by Changing 'Y' & 'N' to 'Yes' & 'No'. update HousingData set SoldAsVacant = case when SoldAsVacant = 'Y' then 'Yes' when SoldAsVacant = 'N' then 'No' else SoldAsVacant end select SoldAsVacant from HousingData --Checking & Removing Duplicate Records (If Any). select [UniqueID ], count(UniqueID) from HousingData group by [UniqueID ] having count(UniqueID)>1 --No Duplicates According to UniqueID --Removing Unused Columns alter table HousingData drop column PropertyAddress, OwnerAddress, TaxDistrict; select * from HousingData
true
3c8cde45f43953ecd2b20c24275bc09785131aed
SQL
jabautista/GeniisysSCA
/src/main/resources/sql/procedures/bae_get_module_parameters.prc
UTF-8
2,340
2.84375
3
[]
no_license
DROP PROCEDURE CPI.BAE_GET_MODULE_PARAMETERS; CREATE OR REPLACE PROCEDURE CPI.BAE_get_module_parameters ( var_module_item_no IN giac_module_entries.item_no%type, var_module_name IN giac_modules.module_name%type, var_gl_acct_category IN OUT giac_module_entries.gl_acct_category%type, var_gl_control_acct IN OUT giac_module_entries.gl_control_acct%type, var_gl_sub_acct_1 IN OUT giac_module_entries.gl_sub_acct_1%type, var_gl_sub_acct_2 IN OUT giac_module_entries.gl_sub_acct_2%type, var_gl_sub_acct_3 IN OUT giac_module_entries.gl_sub_acct_3%type, var_gl_sub_acct_4 IN OUT giac_module_entries.gl_sub_acct_4%type, var_gl_sub_acct_5 IN OUT giac_module_entries.gl_sub_acct_5%type, var_gl_sub_acct_6 IN OUT giac_module_entries.gl_sub_acct_6%type, var_gl_sub_acct_7 IN OUT giac_module_entries.gl_sub_acct_7%type, var_intm_type_level IN OUT giac_module_entries.intm_type_level%type, var_ca_treaty_type_level IN OUT giac_module_entries.ca_treaty_type_level%type, var_line_dependency_level IN OUT giac_module_entries.line_dependency_level%type, var_old_new_acct_level IN OUT giac_module_entries.old_new_acct_level%type, var_dr_cr_tag IN OUT giac_module_entries.dr_cr_tag%type ) is BEGIN SELECT gl_acct_category , gl_control_acct , gl_sub_acct_1 , gl_sub_acct_2 , gl_sub_acct_3 , gl_sub_acct_4 , gl_sub_acct_5 , gl_sub_acct_6 , gl_sub_acct_7 , intm_type_level , line_dependency_level , old_new_acct_level , dr_cr_tag , ca_treaty_type_level INTO var_gl_acct_category , var_gl_control_acct , var_gl_sub_acct_1 , var_gl_sub_acct_2 , var_gl_sub_acct_3 , var_gl_sub_acct_4 , var_gl_sub_acct_5 , var_gl_sub_acct_6 , var_gl_sub_acct_7 , var_intm_type_level , var_line_dependency_level , var_old_new_acct_level , var_dr_cr_tag , var_ca_treaty_type_level FROM giac_module_entries a, giac_modules b WHERE a.module_id = b.module_id AND module_name = var_module_name AND item_no = VAR_MODULE_ITEM_NO ; EXCEPTION WHEN NO_DATA_FOUND THEN null; END; /
true
54bfb8d74b11fab2f5287f11b59d04326a9f4b53
SQL
Amandaalmeida12/foodsearch
/db/19_11_2017.sql
UTF-8
6,273
2.984375
3
[]
no_license
-- MySQL dump 10.13 Distrib 5.7.20, for Linux (x86_64) -- -- Host: localhost Database: foodsearch_db -- ------------------------------------------------------ -- Server version 5.7.20-0ubuntu0.16.04.1 /*!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 */; /*!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 `images` -- DROP TABLE IF EXISTS `images`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `images` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `photo` varchar(255) NOT NULL, `photo_dir` varchar(255) DEFAULT NULL, `profile_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `fk_image_profile` (`profile_id`), CONSTRAINT `fk_image_profile` FOREIGN KEY (`profile_id`) REFERENCES `profiles` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `images` -- LOCK TABLES `images` WRITE; /*!40000 ALTER TABLE `images` DISABLE KEYS */; INSERT INTO `images` VALUES (1,'download.jpeg','',3); /*!40000 ALTER TABLE `images` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `menus` -- DROP TABLE IF EXISTS `menus`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `menus` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(20) NOT NULL, `price` float DEFAULT NULL, `category` varchar(45) NOT NULL, `description` text, `photo` varchar(255) DEFAULT NULL, `photo_dir` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `menus` -- LOCK TABLES `menus` WRITE; /*!40000 ALTER TABLE `menus` DISABLE KEYS */; INSERT INTO `menus` VALUES (25,'batatas',2,'frituras','jnm','download.jpeg',''); /*!40000 ALTER TABLE `menus` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `profile_menus` -- DROP TABLE IF EXISTS `profile_menus`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `profile_menus` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `profile_id` int(10) unsigned NOT NULL, `menu_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `fk_profile_id` (`profile_id`), KEY `fk_profile_menu` (`menu_id`), CONSTRAINT `fk_profile_id` FOREIGN KEY (`profile_id`) REFERENCES `profiles` (`id`) ON DELETE CASCADE, CONSTRAINT `fk_profile_menu` FOREIGN KEY (`menu_id`) REFERENCES `menus` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `profile_menus` -- LOCK TABLES `profile_menus` WRITE; /*!40000 ALTER TABLE `profile_menus` DISABLE KEYS */; INSERT INTO `profile_menus` VALUES (3,3,25); /*!40000 ALTER TABLE `profile_menus` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `profiles` -- DROP TABLE IF EXISTS `profiles`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `profiles` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(200) NOT NULL, `address` varchar(200) NOT NULL, `operation` varchar(20) NOT NULL, `contact` varchar(20) NOT NULL, `description` text NOT NULL, `photo` varchar(255) NOT NULL, `photo_dir` varchar(255) DEFAULT NULL, `user_id` int(10) unsigned NOT NULL, `lat` float(10,6) NOT NULL, `lng` float(10,6) NOT NULL, PRIMARY KEY (`id`), KEY `fk_profile_user` (`user_id`), CONSTRAINT `fk_profile_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `profiles` -- LOCK TABLES `profiles` WRITE; /*!40000 ALTER TABLE `profiles` DISABLE KEYS */; INSERT INTO `profiles` VALUES (3,'mercado','kmmk','km','451','km,','gato-gif.gif','',14,4.000000,2.000000); /*!40000 ALTER TABLE `profiles` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(100) NOT NULL, `email` varchar(60) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `users` -- LOCK TABLES `users` WRITE; /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` VALUES (14,'katia','[email protected]','$2y$10$WKOtKd9N9sx9pr9IixOW5uO0GJTSA0nWNJ0ltDoXOdYwTSIWfAVqW'),(15,'amandacasttro','[email protected]','$2y$10$k7DoFTuNfe40.jhxcpIRuO55RyJrUQuDBI8I4It/NSAfXrsH6CDNW'),(16,'amanda','[email protected]','$2y$10$gSCpgnnVSB8Sm6W5pQD5EeCh1AmwMpKSk/lFgoXM6Hdg0IQck8QKu'),(26,'amnmghjhg','[email protected]','$2y$10$FSiXOWkMC4d0O9tK39ka7.dc5G0u/VYIlDMrtonvufadk36iA0SDK'); /*!40000 ALTER TABLE `users` 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 2017-11-19 21:56:00
true
020868f6fb7b789f6c22650eeedcbde001eb4d6c
SQL
bkiers/sqlite-parser
/src/test/resources/e_fkey.test_27.sql
UTF-8
562
3.125
3
[ "MIT" ]
permissive
-- e_fkey.test -- -- execsql { -- CREATE TABLE artist( -- artistid INTEGER PRIMARY KEY, -- artistname TEXT -- ); -- CREATE TABLE track( -- trackid INTEGER, -- trackname TEXT, -- trackartist INTEGER NOT NULL, -- FOREIGN KEY(trackartist) REFERENCES artist(artistid) -- ); -- } CREATE TABLE artist( artistid INTEGER PRIMARY KEY, artistname TEXT ); CREATE TABLE track( trackid INTEGER, trackname TEXT, trackartist INTEGER NOT NULL, FOREIGN KEY(trackartist) REFERENCES artist(artistid) );
true
4208893dfd13c1a2edfc19e10ec186075599db1b
SQL
kevin-meng/learn-data-analysis-the-hard-way
/SQL/interview/solutions/Q24:查询学生平均成绩及其名次.sql
UTF-8
2,452
4.34375
4
[]
no_license
-- ######################################################## -- Q24:查询学生平均成绩及其名次 -- ######################################################## --24.1 查询学生的平均成绩并进行排名,sql 2000用子查询完成,分平均成绩重复时保留名次空缺和不保留名次空缺两种。 select t1.*, px = ( select count(1) from ( select m.SID 学生编号, m.Sname 学生姓名, isnull(cast(avg(score) as decimal(18, 2)), 0) 平均成绩 from Student m left join SC n on m.SID = n.SID group by m.SID, m.Sname ) t2 where 平均成绩 > t1.平均成绩 ) + 1 from ( select m.SID 学生编号, m.Sname 学生姓名, isnull(cast(avg(score) as decimal(18, 2)), 0) 平均成绩 from Student m left join SC n on m.SID = n.SID group by m.SID, m.Sname ) t1 order by px select t1.*, px = ( select count(distinct 平均成绩) from ( select m.SID 学生编号, m.Sname 学生姓名, isnull(cast(avg(score) as decimal(18, 2)), 0) 平均成绩 from Student m left join SC n on m.SID = n.SID group by m.SID, m.Sname ) t2 where 平均成绩 >= t1.平均成绩 ) from ( select m.SID 学生编号, m.Sname 学生姓名, isnull(cast(avg(score) as decimal(18, 2)), 0) 平均成绩 from Student m left join SC n on m.SID = n.SID group by m.SID, m.Sname ) t1 order by px; --24.2 查询学生的平均成绩并进行排名,sql 2005用rank,DENSE_RANK完成,分平均成绩重复时保留名次空缺和不保留名次空缺两种。 select t.*, px = rank() over( order by 平均成绩 desc ) from ( select m.SID 学生编号, m.Sname 学生姓名, isnull(cast(avg(score) as decimal(18, 2)), 0) 平均成绩 from Student m left join SC n on m.SID = n.SID group by m.SID, m.Sname ) t order by px select t.*, px = DENSE_RANK() over( order by 平均成绩 desc ) from ( select m.SID 学生编号, m.Sname 学生姓名, isnull(cast(avg(score) as decimal(18, 2)), 0) 平均成绩 from Student m left join SC n on m.SID = n.SID group by m.SID, m.Sname ) t order by px;
true
7131335d1a037811f29889d77ea7c153bf420b31
SQL
richnamk/python_nov_2017
/richardN/mySqlQueries/friendships/queryCommands
UTF-8
899
3.375
3
[]
no_license
INSERT INTO users (first_name, last_name, created_at, updated_at) VALUES ('Chris','Baker', NOW(), NOW() ); INSERT INTO users (first_name, last_name, created_at, updated_at) VALUES ('Dianna','Smith', NOW(), NOW() ); INSERT INTO users (first_name, last_name, created_at, updated_at) VALUES ('James','Johnson', NOW(), NOW() ); INSERT INTO users (first_name, last_name, created_at, updated_at) VALUES ('Jessica','Davidson', NOW(), NOW() ); INSERT INTO friendships (users_id, friend_id) VALUES(1,4); INSERT INTO friendships (users_id, friend_id) VALUES(2,1); INSERT INTO friendships (users_id, friend_id) VALUES(3,4); SELECT users.first_name, users.last_name, users1.first_name AS friend_first_name, users1.last_name AS friend_last_name FROM users LEFT JOIN friendships ON users.id = friendships.users_id LEFT JOIN users AS users1 ON friendships.friend_id = users1.id ORDER BY friend_last_name;
true
e10c753881fa626e8062795902c5ee19b362fca9
SQL
ShinMinGyeong006/Studysqlserver
/sql/07_Tt-sql/210209_join_example.sql
UTF-8
419
3.15625
3
[]
no_license
select * from userTbl; select * from buyTbl; select * from userTbl where userid='Jyp'; select * from buyTbl where userid='Jyp'; select * from buyTbl where userid='bbk'; --inner join select u.username,u.addr, concat(u.mobile1,'-', left(u.mobile2,4),'-',right(u.mobile2,4)) as mobile, b.prodName,b.price,b.amount from buyTbl as b inner join userTbl as u on b.userID = u.userID where b.userID = 'jyp';
true
e02c753f7c6da4c5adb392004f895cfdea83dd80
SQL
JoseManuelLopezBocanegra/BDNBA
/src/DecepctionEntertainment/NBA/sql/CreacionTablas.sql
UTF-8
1,258
3.328125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Author: manul * Created: 22-abr-2019 */ CREATE TABLE EQUIPOS ( ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, NOMBRE VARCHAR(40) NOT NULL, FECHA_FUNDACIÓN DATE, PRESUPUESTO DECIMAL(15,2), CIUDAD VARCHAR(40), ESTADIO VARCHAR(50), NºCAMPEONATOS SMALLINT, DIVISIÓN VARCHAR(20), CONFERENCIA VARCHAR(20), ESCUDO VARCHAR(50), CONSTRAINT ID_EQUIPOS_PK PRIMARY KEY (ID) ); CREATE TABLE JUGADORES ( ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, NOMBRE VARCHAR(20) NOT NULL, APELLIDOS VARCHAR(40) NOT NULL, NºCAMISETA CHAR(2), POSICIÓN VARCHAR(10), PAÍS VARCHAR(20), PROMEDIO_PUNTOS_POR_PARTIDO DECIMAL(10,2), ALTURA DECIMAL(10,2), FECHA_NACIMIENTO DATE, SALARIO DECIMAL(15,2), EQUIPO INTEGER NOT NULL, AÑOS_ACTIVO SMALLINT, ANILLOS SMALLINT, ALL_STAR BOOLEAN, NºALL_STARS SMALLINT, MVP SMALLINT, FOTO VARCHAR(30), CONSTRAINT ID_JUGADORES_PK PRIMARY KEY (ID), CONSTRAINT E_JUGADORES_FK FOREIGN KEY (EQUIPO) REFERENCES EQUIPOS (ID) );
true
ba6fa42b5f88670047d63eb6255275ecf1dd4897
SQL
nikhil199710/Employee_Payroll_Problem
/UC3_Insert data.sql
UTF-8
399
2.9375
3
[]
no_license
/* UC 3 : Insert data into the table */ use payroll_service; /* Creating a table */ create table employee_payroll (EmpID int not null identity(1,1) primary key, EmpName varchar(150) not null, Salary float not null, StartDate date not null ); /* Inserting data into table */ insert into employee_payroll(EmpName,Salary,StartDate) values ('Nikhil',72000,'2020-09-18'), ('Morgan',180000,'2020-10-26');
true
b03ef58e9d97ffc5de01d18e4f209fd5e146d081
SQL
vti/object-db1
/t/test_schema/mysql.sql
UTF-8
1,650
3.046875
3
[]
no_license
CREATE TABLE `category` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT, `author_id` INTEGER, `title` varchar(40) default '' ) TYPE=innodb; CREATE TABLE `article` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT, `category_id` INTEGER, `author_id` INTEGER, `title` varchar(40) default '' ) TYPE=innodb; CREATE TABLE `comment` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT, `master_id` INTEGER, `type` varchar(40) default '', `content` varchar(40) default '' ) TYPE=innodb; CREATE TABLE `podcast` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT, `author_id` INTEGER, `title` varchar(40) default '' ) TYPE=innodb; CREATE TABLE `tag` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT, `name` varchar(40) default '' ) TYPE=innodb; CREATE TABLE `article_tag_map` ( `article_id` INTEGER, `tag_id` INTEGER, PRIMARY KEY(`article_id`, `tag_id`) ) TYPE=innodb; CREATE TABLE `author` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT, `name` varchar(40) default '', `password` varchar(40) default '', UNIQUE(`name`) ) TYPE=innodb; CREATE TABLE `author_admin` ( `author_id` INTEGER PRIMARY KEY, `beard` varchar(40) default '' ) TYPE=innodb; CREATE TABLE `nested_comment` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT, `parent_id` INTEGER, `master_id` INTEGER NOT NULL, `master_type` VARCHAR(20) NOT NULL , `path` VARCHAR(255), `level` INTEGER NOT NULL , `content` VARCHAR(1024) NOT NULL, `addtime` INTEGER NOT NULL, `lft` INTEGER NOT NULL, `rgt` INTEGER NOT NULL ) TYPE=innodb; CREATE TABLE `family` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT, `parent_id` INTEGER, `name` VARCHAR(255) ) TYPE=innodb;
true
c74c23a0cf50b79a5c5164b1e77d8c578c72c303
SQL
ligy2016/mysql
/gaoxiao_sql_bk/obj_prod_update_ccnt_blnc.sql
UTF-8
4,485
3.546875
4
[]
no_license
/* SQLyog Enterprise v12.09 (64 bit) MySQL - 5.7.20-log : Database - feps ********************************************************************* */ /*!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 */; USE `feps`; /* Procedure structure for procedure `prod_update_ccnt_blnc` */ DELIMITER $$ /*!50003 CREATE DEFINER=`qlqqmn`@`%` PROCEDURE `prod_update_ccnt_blnc`(OUT `res` char(1), IN `type1` char(1), IN `type2` char(1), IN `amount` decimal(19,3), IN `fuacct` varchar(18), IN `sub2fuacct` int, IN `sub3fuacct` int) BEGIN ##名称 #prod_update_ccnt_blnc ##作用 #更新资产账户余额 #业务引起的资金变动统一使用此过程 #此过程不处理充值和提现 ##参数说明 #OUT `res` char(1), IN `type1` char(1), IN `type2` char(1), IN `amount` decimal(19,3), IN `fuacct` varchar(18), IN `sub2fuacct` int, IN `sub3fuacct` int #res:返回值('0':成功, '1':失败) #type1:账户类型('0':2级账户, '1':可用交易资金子账户, '2':冻结交易资金子账户, '3':冻结保证金子账户(仅期权有效), '4':实际占用保证金子账户(仅期权有效)) #type2:操作类型('0':转入 '1':转出 '2':冻结 '3':解冻 '4': 冻结后转出) ##主体 DECLARE TotalBal decimal(19,3) DEFAULT(0.0); DECLARE AvalBal decimal(19,3) DEFAULT(0.0); SET res = '0'; ##二级账户 IF(type1 = '0') THEN IF(type2 = '0') THEN UPDATE tcasub2balance SET Fd_TotalBal = Fd_TotalBal + amount, Fd_AvalBal = Fd_AvalBal + amount WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct; ELSEIF(type2 = '1') THEN SELECT Fd_TotalBal, Fd_AvalBal INTO TotalBal, AvalBal FROM tcasub2balance WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct FOR UPDATE; IF(TotalBal < amount OR AvalBal < amount) THEN SET res = '1'; ELSE UPDATE tcasub2balance SET Fd_TotalBal = Fd_TotalBal - amount, Fd_AvalBal = Fd_AvalBal - amount WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct; END IF; ELSEIF(type2 = '2') THEN SELECT Fd_AvalBal INTO AvalBal FROM tcasub2balance WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct FOR UPDATE; IF(AvalBal < amount) THEN SET res = '1'; ELSE UPDATE tcasub2balance SET Fd_AvalBal = Fd_AvalBal - amount WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct; END IF; ELSEIF(type2 = '3') THEN UPDATE tcasub2balance SET Fd_AvalBal = Fd_AvalBal + amount WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct; ELSEIF(type2 = '4') THEN SELECT Fd_TotalBal INTO @TotalBal FROM tcasub2balance WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct FOR UPDATE; if(ABS(@TotalBal - amount) <= 0.0001) THEN UPDATE tcasub2balance SET Fd_TotalBal = 0.0 WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct; ELSEIF(@TotalBal < amount ) THEN #ROLLBACK; SET res = '1'; ELSE UPDATE tcasub2balance SET Fd_TotalBal = Fd_TotalBal - amount WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct; END IF; ELSE SET res = '1'; END IF; ##三级账户 ELSEIF(type1 = '1' OR type1 = '2' OR type1 = '3' OR type1 = '4') THEN IF(type2 = '0') THEN UPDATE tcasub3balance SET Fd_Balance = Fd_Balance + amount WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct AND fi_sub3fuacct = sub3fuacct; ELSEIF(type2 = '1') THEN SELECT Fd_Balance INTO TotalBal FROM tcasub3balance WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct AND fi_sub3fuacct = sub3fuacct FOR UPDATE; IF(TotalBal < amount) THEN SET res = '1'; ELSE UPDATE tcasub3balance SET Fd_Balance = Fd_Balance - amount WHERE fs_fuacct = fuacct AND fi_sub2fuacct = sub2fuacct AND fi_sub3fuacct = sub3fuacct; END IF; ELSE SET res = '1'; END IF; ELSE SET res = '1'; END IF; END */$$ DELIMITER ; /*!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
b7bcf25e05c335a91d8b3781773e46da5bcea92b
SQL
rhirning/nicki-consulting
/nicki-consulting-core/db/derby/create_CUSTOMERS.sql
UTF-8
376
2.609375
3
[]
no_license
DROP TABLE APP.CUSTOMERS; CREATE TABLE APP.CUSTOMERS ( ID bigint NOT NULL GENERATED ALWAYS AS IDENTITY, NAME varchar(1000) NOT NULL, PARENT_ID bigint, ALIAS varchar(1000), STREET varchar(1000), ZIP varchar(1000), CITY varchar(1000), INVOICE_TEMPLATE varchar(1000), TIMESHEET_TEMPLATE varchar(1000), CONSTRAINT CUSTOMERS_PK PRIMARY KEY (ID) );
true
daede74a2e4230bb1a8ea10cee7fdc3f7744948e
SQL
He-Ze/Web-SYSU
/大作业/test/dataset/blogger_likes.sql
UTF-8
847
2.8125
3
[ "MIT" ]
permissive
create table likes ( lid int auto_increment primary key, blogId int not null, userId varchar(255) null ); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (1, 1, 'gth'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (2, 1, 'heze'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (3, 1, 'user'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (4, 2, 'user2'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (5, 3, 'user'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (6, 3, 'heze'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (7, 4, 'gth'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (8, 5, 'user3'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (9, 2, 'wsc'); INSERT INTO blogger.likes (lid, blogId, userId) VALUES (10, 6, 'wsc');
true
a0c06544ffb982597ad4b555a8cc027019f7ea89
SQL
Gemy95/Back-End-EasyKashTask
/create database/create and insert queries.sql
UTF-8
1,608
3.359375
3
[]
no_license
create database if not exists easykashtaskdb; use EasyKashTaskDB ; CREATE TABLE IF Not Exists Seller ( seller_id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(30) NOT NULL, last_name VARCHAR(30) NOT NULL, email VARCHAR(50) NOT NULL, phone_number VARCHAR(50) NOT NULL, address VARCHAR(50) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON Update CURRENT_TIMESTAMP ); Insert Into easykashtaskdb.seller(first_name,last_name,email,phone_number,address) values ("ali","gamal","[email protected]","01017431767","assiut"); CREATE TABLE IF Not Exists Transaction ( transaction_id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY, seller_id INT(10) UNSIGNED NOT NULL, offer_id INT(10) UNSIGNED NOT NULL, title VARCHAR(30) NOT NULL, fees DOUBLE(30,5) NOT NULL, amount DOUBLE(30,5) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON Update CURRENT_TIMESTAMP ); Insert Into easykashtaskdb.transaction(seller_id,title,fees,amount) Values (1,"payment",20,500) ; CREATE TABLE IF Not Exists Offer( offer_id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY, seller_id INT(10) UNSIGNED NOT NULL, offer_type VARCHAR(30) NOT NULL, offer_code VARCHAR(30) NOT NULL, offer_discount DOUBLE(30,5) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON Update CURRENT_TIMESTAMP ); INSERT INTO `easykashtaskdb`.`offer` (`offer_id`, `seller_id`, `offer_type`, `offer_code`, `offer_discount`) VALUES ('1', '1', 'promo', 'xyz123', '20');
true
1ca240d5c132a81600053c662af22da47b272011
SQL
OneSharpeGuy/prime
/sts/osg_singout_support/osg_users.sql
UTF-8
872
3.765625
4
[]
no_license
SELECT u.uid, u.name AS u_name, u.mail, d.name AS voice_part, d.tid, ifnull(m.hit,0) as is_member, ifnull(n.hit,1) as is_singer, CASE u.uid WHEN 1 THEN 1 ELSE ifnull(a.hit,0) END AS is_admin FROM users u LEFT JOIN field_data_field_voice_part p ON u.uid = p.entity_id LEFT JOIN taxonomy_term_data d ON d.tid = p.field_voice_part_tid LEFT JOIN (SELECT a.uid, 1 AS hit FROM `role` b INNER JOIN users_roles a ON a.rid=b.rid WHERE b.name='member') m ON u.uid=m.uid LEFT JOIN (SELECT a.uid, 0 AS hit FROM `role` b INNER JOIN users_roles a ON a.rid=b.rid WHERE b.name='non singer') n ON u.uid=n.uid LEFT JOIN (SELECT a.uid, 1 AS hit FROM `role` b INNER JOIN users_roles a ON (a.rid=b.rid) WHERE b.name='administrator') a ON u.uid=n.uid
true
50eaa81fc3b7ef5aa47b6c00cabb458d9749ff2c
SQL
qk27015/Introduction-to-practical-SQL
/03/002_union.sql
UTF-8
231
2.8125
3
[]
no_license
-- UNIONを用いた条件分岐 -- 実行計画が冗長になる select item_name, year, price_tax_ex as price from Items where year <= 2001 union all select item_name, year, price_tax_in as price from Items where year >= 2002;
true
3a8216bca9ebfd434f0c276e4b66cc1f98eab702
SQL
strongyoung/spider
/sql/selectSeed.sql
UTF-8
391
2.625
3
[]
no_license
delimiter $$ use forconsumer ; drop procedure if exists selectSeed; create procedure selectSeed( in iStart int, in iNum int, in vown varchar(50)) begin if iNum is null or iNum = 0 then select * from seed where is_visited=0 and is_valid=1 and own=vown; else select * from seed where is_visited=0 and is_valid=1 and own=vown limit iStart,iNum; end if ; end $$ delimiter ;
true
abdc032370aae243583232c4f4218a1eca42461d
SQL
Tong-Chen/eg
/config/mm9/makeDb.sql
UTF-8
2,422
2.625
3
[]
no_license
drop table if exists config; create table config ( bbiPath text not null, seqPath text null, defaultGenelist text not null, defaultCustomtracks text not null, defaultPosition varchar(255) not null, defaultDataset varchar(255) not null, defaultDecor text null, defaultScaffold text null, hasGene boolean not null, allowJuxtaposition boolean not null, keggSpeciesCode varchar(255) not null, information text not null, runmode tinyint not null, initmatplot boolean not null ); insert into config values( "/srv/epgg/data/data/subtleKnife/mm9/", "/srv/epgg/data/data/subtleKnife/seq/mm9.gz", "CYP4Z1\\nCYP2A7\\nCYP2A6\\nCYP3A4\\nCYP1A1\\nCYP4V2\\nCYP51A1\\nCYP2C19\\nCYP26B1\\nCYP11B2\\nCYP24A1\\nCYP4B1\\nCYP2C8", "{3:{url:'http://vizhub.wustl.edu/hubSample/mm9/wgEncodeLicrHistoneBatInputMAdult24wksC57bl6StdSig.gz',name:'test track'},1:{url:'http://vizhub.wustl.edu/hubSample/mm9/bed.gz',name:'test track'},5:{url:'http://vizhub.wustl.edu/hubSample/mm9/wgEncodeLicrHistoneBatInputMAdult24wksC57bl6StdAlnRep2.gz',name:'test track'},100:{url:'http://vizhub.wustl.edu/hubSample/mm9/hub'},21:{hg19:'http://vizhub.wustl.edu/public/mm9/weaver/mm9_hg19_axt.gz',rn4:'http://vizhub.wustl.edu/public/mm9/weaver/mm9_rn4_axt.gz'}}", "chr6,51999773,chr6,52368420", "longrange,encode", "refGene,rmsk_all", "chr1,chr2,chr3,chr4,chr5,chr6,chr7,chr8,chr9,chr10,chr11,chr12,chr13,chr14,chr15,chr16,chr17,chr18,chr19,chrX,chrY,chrM", true, true, "mmu", "Assembly version|mm9|Sequence source|<a href=http://hgdownload.cse.ucsc.edu/goldenPath/mm9/bigZips/ target=_blank>UCSC browser</a>|Date parsed|August 1, 2011|Chromosomes|22|Misc|13|Total bases|3,137,144,693|Logo art|<a href=http://free-extras.com/images/mouse-8552.htm target=_blank>link</a>", 0, false ); drop table if exists tempURL; create table tempURL ( session varchar(100) not null, offset INT unsigned not null, urlpiece text not null ); drop table if exists scaffoldInfo; create table scaffoldInfo ( parent varchar(255) not null, child varchar(255) not null, childLength int unsigned not null ); load data local infile "scaffoldInfo" into table scaffoldInfo; drop table if exists cytoband; create table cytoband ( id int null auto_increment primary key, chrom char(20) not null, start int not null, stop int not null, name char(20) not null, colorIdx int not null ); load data local infile "cytoband" into table cytoband;
true
7a37094d3cd52f485c625b005a3da8cd19c791e4
SQL
OvidiuEDSgrup/CARMOLACT
/Stored Procedures/Procs1/CompletezDateReceptiiSF.sql
UTF-8
774
3.25
3
[]
no_license
CREATE procedure CompletezDateReceptiiSF @Sub char(9), @Tip char(2), @Numar char(8), @Data datetime AS if OBJECT_ID('tempdb..#yso_pozdocsf') is not null drop table #yso_pozdocsf select p.idPozDoc ,f.Valoare, f.TVA_22 into #yso_pozdocsf from pozdoc p inner join facturi f on f.Subunitate=p.Subunitate and f.Tip=0x54 and f.Tert=p.Tert and f.Factura=p.Cod_intrare where p.Subunitate=@Sub and p.Tip=@Tip and p.Numar=@Numar and p.Data=@Data and p.Cod='SOF' and p.Cont_de_stoc like '408%' and p.Cod_intrare<>'' and p.Pret_de_stoc<>f.Valoare and p.Pret_valuta<>f.Valoare and p.TVA_deductibil<>f.TVA_22 if @@ROWCOUNT>0 update p set Pret_valuta=t.Valoare, Pret_de_stoc=t.TVA_22, TVA_deductibil=t.TVA_22 from pozdoc p inner join #yso_pozdocsf t on t.idPozDoc=p.idPozDoc
true
7408bac057c2b99a42cb658925d2505b44b38172
SQL
ku5-ku5/CM2305-Voting-System-Prototype-
/Scripts/SQL Scripts/Politicians_Table.sql
UTF-8
914
2.53125
3
[]
no_license
CREATE TABLE Political_Party( UId CHAR(38) NOT NULL, Name VARCHAR(255) NOT NULL, PRIMARY KEY (UId) ); INSERT INTO `votedb`.`political_party` (`UId`, `Name`) VALUES ('c5a60d73-ffe0-11e9-8f05-1831bf97a796', 'Labour'); INSERT INTO `votedb`.`political_party` (`UId`, `Name`) VALUES ('c5a7721d-ffe0-11e9-8f05-1831bf97a796', 'Conservative'); INSERT INTO `votedb`.`political_party` (`UId`, `Name`) VALUES ('c5a8f70d-ffe0-11e9-8f05-1831bf97a796', 'UKIP'); INSERT INTO `votedb`.`political_party` (`UId`, `Name`) VALUES ('c5aae837-ffe0-11e9-8f05-1831bf97a796', 'Green Party'); INSERT INTO `votedb`.`political_party` (`UId`, `Name`) VALUES ('29478d29-0489-11ea-be81-1831bf97a796', 'DUP'); INSERT INTO `votedb`.`political_party` (`UId`, `Name`) VALUES ('2948f383-0489-11ea-be81-1831bf97a796', 'SNP'); INSERT INTO `votedb`.`political_party` (`UId`, `Name`) VALUES ('294980dc-0489-11ea-be81-1831bf97a796', 'Plaid Cymru');
true
8872e51c5232df5c6f42819b53708253285cff0d
SQL
sprokushev/Delphi
/MASTER/_DATABASE/Tables/MASTER_KLS_STRUCTURE.sql
WINDOWS-1251
2,083
3.375
3
[]
no_license
-- -- MASTER_KLS_STRUCTURE (Table) -- CREATE TABLE MASTER.MASTER_KLS_STRUCTURE ( ID VARCHAR2(50 BYTE) NOT NULL, CAPTION VARCHAR2(100 BYTE), SORTBY NUMBER(3), TABLE_NAME VARCHAR2(50 BYTE), UNIQUE_FIELD VARCHAR2(30 BYTE) DEFAULT 'ID', QUERY VARCHAR2(1024 BYTE), START_ORDER VARCHAR2(50 BYTE), SEQUENCES VARCHAR2(30 BYTE), NAME_FIELD VARCHAR2(30 BYTE), NAME_FIELD_2 VARCHAR2(30 BYTE), DATE_FIELD_BEGIN VARCHAR2(15 BYTE), DATE_FIELD_END VARCHAR2(15 BYTE), VIEW_TIME NUMBER(1) DEFAULT 0, FILTER_1 VARCHAR2(30 BYTE), FILTER_1_CAPTION VARCHAR2(50 BYTE), FILTER_2 VARCHAR2(30 BYTE), FILTER_2_CAPTION VARCHAR2(50 BYTE), FILTER_3 VARCHAR2(30 BYTE), FILTER_3_CAPTION VARCHAR2(50 BYTE), ADD_FORM VARCHAR2(30 BYTE), RIGHTS_ID VARCHAR2(30 BYTE), FOX_UPDATE_QUERY VARCHAR2(300 BYTE), FOX_INSERT_QUERY VARCHAR2(300 BYTE), FOX_DELETE_QUERY VARCHAR2(300 BYTE), UNIQID_SELECT_QUERY VARCHAR2(300 BYTE), UNIQID_UPDATE_QUERY VARCHAR2(300 BYTE), CHILD_FORM VARCHAR2(30 BYTE), CHILD_NAME VARCHAR2(30 BYTE), FROZEN_COLS NUMBER(2), MASTER_FIELD VARCHAR2(30 BYTE) ) TABLESPACE USERS2 NOCOMPRESS ; COMMENT ON TABLE MASTER.MASTER_KLS_STRUCTURE IS ' '; COMMENT ON COLUMN MASTER.MASTER_KLS_STRUCTURE.VIEW_TIME IS ' ( "")'; COMMENT ON COLUMN MASTER.MASTER_KLS_STRUCTURE.CHILD_FORM IS ' '; COMMENT ON COLUMN MASTER.MASTER_KLS_STRUCTURE.CHILD_NAME IS ' "" '; COMMENT ON COLUMN MASTER.MASTER_KLS_STRUCTURE.FROZEN_COLS IS '" "'; COMMENT ON COLUMN MASTER.MASTER_KLS_STRUCTURE.MASTER_FIELD IS ' -';
true
f7ea7782e14566900fc064df44c5adaca4ee641f
SQL
lidianzhe/sqlscript
/Iris/inout.sql
UTF-8
248
2.546875
3
[]
no_license
PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE InoutDetails( PId integer not null primary key autoincrement, DeviceNo varchar(20) , PersonId int null, CardTime datetime, Flag tinyint, SeriesId tinyint, if_UserNo integer ); COMMIT;
true
dfbe4411294fce121245cff30410f9c6ca44e319
SQL
AlexeyTiunov/avtodok.com.ua
/bitrix/php_interface/include/autodoc_preprocess_tmp_db.sql
UTF-8
619
2.8125
3
[]
no_license
-- Ищем текущий ID для всех товаров во временной таблице UPDATE b_autodoc_import_temp AS t1, b_autodoc_items_m AS t2 SET t1.CurItemID = t2.id WHERE t1.ItemCode = t2.ItemCode AND t1.BrandCode = t2.BrandCode ; -- Работа с ценами -- Ищем текущий ID цены для всех товаров во временной таблице UPDATE b_autodoc_import_temp AS t1, b_autodoc_prices_m AS t2 SET t1.CurPriceID = t2.id WHERE t1.ItemCode = t2.ItemCode AND t1.BrandCode = t2.BrandCode AND t1.RegionCode = t2.RegionCode ;
true
2e0e34b7710fa023ae6ea00d2f5fe6e12c03e6b0
SQL
fagan2888/Loan-Canoe
/notebooks/00_sql/03b_interim_wrangle__balanced_rand_samp__bbz.sql
UTF-8
87,612
3.5625
4
[ "MIT" ]
permissive
/***************************************************************************************************************/ /* Purpose: (1) Typecast transform & Generate Simple, Balanced, Random Samples for each year for ingestion */ /* + (2) Union all the samples for the interim dataset for additional wrangling with pandas */ */ /* */ /* Author: Blake Zenuni, Summer 2019 */ /* Date Created: Aug. 01, 2019 */ /* Last Modified: Sep. 06, 2019 */ /* */ /***************************************************************************************************************/ /*---------------------------------------------------------------------------------------------------------*/ --> NB: Latin abbreviation for NOTA BENE, meaning "note well" <-- /*---------------------------------------------------------------------------------------------------------*/ -- NB1: In this SQL script, simple random samples are balanced for outcomes (50/50 loans approved vs. loans denied). -- NB2: Script 03a applies this same logic, but for unbalanced outcomes. /*======================== 03b. Balanced Outcomes - Simple random samples for HMDA 2010-2017 =========================*/ /*--Creating schema and setting users/role for accessibility profiles--*/ CREATE EXTENSION dblink SCHEMA interim_datasets_v2; CREATE SCHEMA interim_datasets ; CREATE ROLE reporting_user WITH LOGIN PASSWORD 'team_loan_canoe2019' ; GRANT USAGE ON SCHEMA interim_datasets TO reporting_user ; GRANT SELECT ON ALL TABLES IN SCHEMA interim_datasets TO reporting_user ; -- CREATE SCHEMA interim_datasets_v2 ; GRANT USAGE ON SCHEMA interim_datasets TO reporting_user ; GRANT SELECT ON ALL TABLES IN SCHEMA interim_datasets TO reporting_user ; /*------------*/ --> z_bz_AWS_paddleloancanoe <--- /*----------------------------------------------------- HMDA 2010 ----------------------------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda10_srandom_bal_25K ; -- WITH hm_10_ap AS --extract the raw data fields for segment of approved loans with loan type = Conventional ( SELECT hm10.action_taken_name As act, hm10.as_of_year, TRIM(LEADING '0' FROM rate_spread) As rate_spread, hm10.tract_to_msamd_income, hm10.population, hm10.agency_abbr, hm10.minority_population, hm10.number_of_owner_occupied_units, hm10.loan_amount_000s, hm10.number_of_1_to_4_family_units, hm10.hud_median_family_income, hm10.applicant_income_000s, hm10.state_abbr, hm10.property_type_name, hm10.owner_occupancy_name, hm10.msamd_name, hm10.lien_status_name, hm10.hoepa_status_name, hm10.co_applicant_sex_name, hm10.co_applicant_ethnicity_name, hm10.co_applicant_race_name_1, hm10.applicant_sex_name, hm10.applicant_race_name_1, hm10.applicant_ethnicity_name, --set Null because all denial reasons are null for approved loans NULL As denial_reason_name_1, NULL AS denial_reason_name_2, NULL AS denial_reason_name_3 FROM usa_mortgage_market.hmda_lar_2010_allrecords hm10 WHERE hm10.action_taken_name = 'Loan originated' AND hm10.loan_type_name = 'Conventional' AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm10.as_of_year Is Not NULL AND hm10.tract_to_msamd_income Is Not Null AND hm10.population Is Not Null AND hm10.minority_population Is Not Null AND hm10.number_of_owner_occupied_units Is Not Null AND hm10.hud_median_family_income Is Not Null AND hm10.applicant_income_000s Is Not Null AND hm10.state_abbr Is Not Null AND hm10.property_type_name Is Not Null AND hm10.owner_occupancy_name Is Not Null AND hm10.msamd_name Is Not Null AND hm10.lien_status_name Is Not Null AND hm10.hoepa_status_name Is Not Null AND hm10.co_applicant_sex_name Is Not Null AND hm10.co_applicant_race_name_1 Is Not Null AND hm10.co_applicant_ethnicity_name Is Not Null AND hm10.applicant_sex_name Is Not Null AND hm10.applicant_race_name_1 Is Not Null AND hm10.applicant_ethnicity_name Is Not Null AND hm10.agency_abbr Is Not Null AND hm10.loan_amount_000s Is Not Null AND hm10.rate_spread Is Not Null AND hm10.number_of_1_to_4_family_units Is Not Null AND hm10.rate_spread != '' AND hm10.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm_10_u_raw) ) , hm_10_de AS --extract the raw data fields for segment of denied loans with loan type = Conventional ( SELECT hm10.action_taken_name As act, hm10.as_of_year, NULL as rate_spread, hm10.tract_to_msamd_income, hm10.population, hm10.agency_abbr, hm10.minority_population, hm10.number_of_owner_occupied_units, hm10.loan_amount_000s, hm10.number_of_1_to_4_family_units, hm10.hud_median_family_income, hm10.applicant_income_000s, hm10.state_abbr, hm10.property_type_name, hm10.owner_occupancy_name, hm10.msamd_name, hm10.lien_status_name, hm10.hoepa_status_name, hm10.co_applicant_sex_name, hm10.co_applicant_ethnicity_name, hm10.co_applicant_race_name_1, hm10.applicant_sex_name, hm10.applicant_race_name_1, hm10.applicant_ethnicity_name, --extract all denial reasons to concatenate in the following CTE hm10.denial_reason_name_1, hm10.denial_reason_name_2, hm10.denial_reason_name_3 FROM usa_mortgage_market.hmda_lar_2010_allrecords hm10 WHERE hm10.action_taken_name = 'Application denied by financial institution' AND hm10.loan_type_name = 'Conventional' AND ( hm10.denial_reason_name_1 Is Not Null Or denial_reason_name_2 Is not Null OR denial_reason_name_3 Is Not Null ) --dropping all missing denied loans without a denial reason AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm10.as_of_year Is Not NULL AND hm10.tract_to_msamd_income Is Not Null AND hm10.population Is Not Null AND hm10.minority_population Is Not Null AND hm10.number_of_owner_occupied_units Is Not Null AND hm10.hud_median_family_income Is Not Null AND hm10.applicant_income_000s Is Not Null AND hm10.state_abbr Is Not Null AND hm10.property_type_name Is Not Null AND hm10.owner_occupancy_name Is Not Null AND hm10.msamd_name Is Not Null AND hm10.lien_status_name Is Not Null AND hm10.hoepa_status_name Is Not Null AND hm10.co_applicant_sex_name Is Not Null AND hm10.co_applicant_race_name_1 Is Not Null AND hm10.co_applicant_ethnicity_name Is Not Null AND hm10.applicant_sex_name Is Not Null AND hm10.applicant_race_name_1 Is Not Null AND hm10.applicant_ethnicity_name Is Not Null AND hm10.agency_abbr Is Not Null AND hm10.loan_amount_000s Is Not Null AND hm10.msamd_name != '' AND hm10.number_of_1_to_4_family_units Is Not Null ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm10_u_raw) ) , hm_10_u_raw AS --UNION ALL for the two segmented CTEs to get balanced dataset of 25K ( SELECT hm_a.* FROM(SELECT * FROM hm_10_ap ORDER BY random() LIMIT 12500) hm_a UNION ALL --note that we take another random sample of 125000 of each 25K randomized sample segment SELECT hm_d.* FROM(SELECT * FROM hm_10_de ORDER BY random() LIMIT 12500) hm_d ) , hmda_2010_transform As ( SELECT --simple binary assignment of 1 or 0 , bc the WHERE clause in this CTE segments the approved/denied subset CASE WHEN hm10.act = 'Loan originated' THEN 1 ELSE 0 END As act_outc, hm10.as_of_year As action_year, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( hm10.rate_spread As Varchar(5)) As NUMERIC ) As rate_spread, --NB: must be num bc of decimals --concatenating denial reasons into one feature on which we do engineering using python CONCAT_WS(', ', hm10.denial_reason_name_1, hm10.denial_reason_name_2, hm10.denial_reason_name_3) as denials, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( CASE WHEN hm10.tract_to_msamd_income IS NULL THEN NULL ELSE hm10.tract_to_msamd_income END As Varchar(5)) As NUMERIC ) As tract_to_msamd_inc, --NB: must be num bc of dec hm10.population As pop, ROUND(hm10.minority_population, 2) As minority_pop_perc, hm10.number_of_owner_occupied_units As num_owoc_units, hm10.number_of_1_to_4_family_units As num_1to4_fam_units, hm10.loan_amount_000s As ln_amt_000s, hm10.hud_median_family_income As hud_med_fm_inc, --must use embedded functions all-in-one to typecast this as integer because raw data stores it as TEXT CAST( CAST( CASE WHEN hm10.applicant_income_000s IS NULL THEN NULL ELSE hm10.applicant_income_000s END As Varchar(5)) As INT ) As applic_inc_000s, CAST(hm10.state_abbr As VARCHAR(5)) As state_abbr, CAST(hm10.property_type_name As VARCHAR(108) ) As property_type_nm, CAST(hm10.owner_occupancy_name As VARCHAR(108)) As own_occ_nm, CAST(hm10.msamd_name As VARCHAR(108)) As msamd_nm, CAST(hm10.lien_status_name As VARCHAR(56)) As lien_status_nm, CAST(hm10.hoepa_status_name As VARCHAR(56)) As hoep_status_nm, CAST(hm10.co_applicant_sex_name As VARCHAR(28)) As co_appl_sex, CAST(hm10.co_applicant_race_name_1 As VARCHAR(28)) As co_appl_race, CAST(hm10.co_applicant_ethnicity_name As VARCHAR(28)) As co_appl_ethn, CAST(hm10.applicant_sex_name As VARCHAR(28)) As applic_sex, CAST(hm10.applicant_race_name_1 As VARCHAR(28)) As applic_race, CAST(hm10.applicant_ethnicity_name As VARCHAR(28)) As applic_ethn, CAST(hm10.agency_abbr As VARCHAR(28)) As agency_abbr FROM hm_10_u_raw hm10 ORDER BY random() ) , hmda_2010_union AS ( SELECT hm_a.* FROM(SELECT * FROM hmda_2010_transform WHERE act_outc = 1 ORDER BY random() LIMIT 12500) hm_a UNION ALL SELECT hm_a.* FROM(SELECT * FROM hmda_2010_transform WHERE act_outc = 0 ORDER BY random() LIMIT 12500) hm_a ) SELECT hm10_u.* INTO interim_datasets_v2.hmda10_srandom_bal_25K FROM hmda_2010_union hm10_u ORDER BY random() ; /*--------------------------- end HMDA 2010 ---------------------------*/ --> END z_bz_AWS_paddleloancanoe <--- /* ==> NB: All subsequent HMDA individual years will apply the same SQL logic from the code above, but will be stripped of comments for length */ ---> z_tn_AWS_paddleloancanoe <--- /*----------------------------------------------------- HMDA 2011 ----------------------------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda11_srandom_bal_25K ; -- WITH hm_11_ap AS --extract the raw data fields for segment of approved loans with loan type = Conventional ( SELECT hm11.action_taken_name As act, hm11.as_of_year, TRIM(LEADING '0' FROM rate_spread) As rate_spread, hm11.tract_to_msamd_income, hm11.population, hm11.agency_abbr, hm11.minority_population, hm11.number_of_owner_occupied_units, hm11.loan_amount_000s, hm11.number_of_1_to_4_family_units, hm11.hud_median_family_income, hm11.applicant_income_000s, hm11.state_abbr, hm11.property_type_name, hm11.owner_occupancy_name, hm11.msamd_name, hm11.lien_status_name, hm11.hoepa_status_name, hm11.co_applicant_sex_name, hm11.co_applicant_ethnicity_name, hm11.co_applicant_race_name_1, hm11.applicant_sex_name, hm11.applicant_race_name_1, hm11.applicant_ethnicity_name, --set Null because all denial reasons are null for approved loans NULL As denial_reason_name_1, NULL AS denial_reason_name_2, NULL AS denial_reason_name_3 FROM public.hmda_lar_2011_allrecords hm11 WHERE hm11.action_taken_name = 'Loan originated' AND hm11.loan_type_name = 'Conventional' AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm11.as_of_year Is Not NULL AND hm11.tract_to_msamd_income Is Not Null AND hm11.population Is Not Null AND hm11.minority_population Is Not Null AND hm11.number_of_owner_occupied_units Is Not Null AND hm11.hud_median_family_income Is Not Null AND hm11.applicant_income_000s Is Not Null AND hm11.state_abbr Is Not Null AND hm11.property_type_name Is Not Null AND hm11.owner_occupancy_name Is Not Null AND hm11.msamd_name Is Not Null AND hm11.lien_status_name Is Not Null AND hm11.hoepa_status_name Is Not Null AND hm11.co_applicant_sex_name Is Not Null AND hm11.co_applicant_race_name_1 Is Not Null AND hm11.co_applicant_ethnicity_name Is Not Null AND hm11.applicant_sex_name Is Not Null AND hm11.applicant_race_name_1 Is Not Null AND hm11.applicant_ethnicity_name Is Not Null AND hm11.agency_abbr Is Not Null AND hm11.loan_amount_000s Is Not Null AND hm11.rate_spread Is Not Null AND hm11.number_of_1_to_4_family_units Is Not Null AND hm11.rate_spread != '' AND hm11.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm_11_u_raw) ) , hm_11_de AS --extract the raw data fields for segment of denied loans with loan type = Conventional ( SELECT hm11.action_taken_name As act, hm11.as_of_year, NULL as rate_spread, hm11.tract_to_msamd_income, hm11.population, hm11.agency_abbr, hm11.minority_population, hm11.number_of_owner_occupied_units, hm11.loan_amount_000s, hm11.number_of_1_to_4_family_units, hm11.hud_median_family_income, hm11.applicant_income_000s, hm11.state_abbr, hm11.property_type_name, hm11.owner_occupancy_name, hm11.msamd_name, hm11.lien_status_name, hm11.hoepa_status_name, hm11.co_applicant_sex_name, hm11.co_applicant_ethnicity_name, hm11.co_applicant_race_name_1, hm11.applicant_sex_name, hm11.applicant_race_name_1, hm11.applicant_ethnicity_name, --extract all denial reasons to concatenate in the following CTE hm11.denial_reason_name_1, hm11.denial_reason_name_2, hm11.denial_reason_name_3 FROM public.hmda_lar_2011_allrecords hm11 WHERE hm11.action_taken_name = 'Application denied by financial institution' AND hm11.loan_type_name = 'Conventional' AND ( hm11.denial_reason_name_1 Is Not Null Or denial_reason_name_2 Is not Null OR denial_reason_name_3 Is Not Null ) --dropping all missing denied loans without a denial reason AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm11.as_of_year Is Not NULL AND hm11.tract_to_msamd_income Is Not Null AND hm11.population Is Not Null AND hm11.minority_population Is Not Null AND hm11.number_of_owner_occupied_units Is Not Null AND hm11.hud_median_family_income Is Not Null AND hm11.applicant_income_000s Is Not Null AND hm11.state_abbr Is Not Null AND hm11.property_type_name Is Not Null AND hm11.owner_occupancy_name Is Not Null AND hm11.msamd_name Is Not Null AND hm11.lien_status_name Is Not Null AND hm11.hoepa_status_name Is Not Null AND hm11.co_applicant_sex_name Is Not Null AND hm11.co_applicant_race_name_1 Is Not Null AND hm11.co_applicant_ethnicity_name Is Not Null AND hm11.applicant_sex_name Is Not Null AND hm11.applicant_race_name_1 Is Not Null AND hm11.applicant_ethnicity_name Is Not Null AND hm11.agency_abbr Is Not Null AND hm11.loan_amount_000s Is Not Null AND hm11.msamd_name != '' AND hm11.number_of_1_to_4_family_units Is Not Null ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm11_u_raw) ) , hm_11_u_raw AS --UNION ALL for the two segmented CTEs to get balanced dataset of 25K ( SELECT hm_a.* FROM(SELECT * FROM hm_11_ap ORDER BY random() LIMIT 12500) hm_a UNION ALL --note that we take another random sample of 125000 of each 25K randomized sample segment SELECT hm_d.* FROM(SELECT * FROM hm_11_de ORDER BY random() LIMIT 12500) hm_d ) , hmda_2011_transform As ( SELECT --simple binary assignment of 1 or 0 , bc the WHERE clause in this CTE segments the approved/denied subset CASE WHEN hm11.act = 'Loan originated' THEN 1 ELSE 0 END As act_outc, hm11.as_of_year As action_year, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( hm11.rate_spread As Varchar(5)) As NUMERIC ) As rate_spread, --NB: must be num bc of decimals --concatenating denial reasons into one feature on which we do engineering using python CONCAT_WS(', ', hm11.denial_reason_name_1, hm11.denial_reason_name_2, hm11.denial_reason_name_3) as denials, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( CASE WHEN hm11.tract_to_msamd_income IS NULL THEN NULL ELSE hm11.tract_to_msamd_income END As Varchar(5)) As NUMERIC ) As tract_to_msamd_inc, --NB: must be num bc of dec hm11.population As pop, ROUND(hm11.minority_population, 2) As minority_pop_perc, hm11.number_of_owner_occupied_units As num_owoc_units, hm11.number_of_1_to_4_family_units As num_1to4_fam_units, hm11.loan_amount_000s As ln_amt_000s, hm11.hud_median_family_income As hud_med_fm_inc, --must use embedded functions all-in-one to typecast this as integer because raw data stores it as TEXT CAST( CAST( CASE WHEN hm11.applicant_income_000s IS NULL THEN NULL ELSE hm11.applicant_income_000s END As Varchar(5)) As INT ) As applic_inc_000s, CAST(hm11.state_abbr As VARCHAR(5)) As state_abbr, CAST(hm11.property_type_name As VARCHAR(118) ) As property_type_nm, CAST(hm11.owner_occupancy_name As VARCHAR(118)) As own_occ_nm, CAST(hm11.msamd_name As VARCHAR(118)) As msamd_nm, CAST(hm11.lien_status_name As VARCHAR(56)) As lien_status_nm, CAST(hm11.hoepa_status_name As VARCHAR(56)) As hoep_status_nm, CAST(hm11.co_applicant_sex_name As VARCHAR(28)) As co_appl_sex, CAST(hm11.co_applicant_race_name_1 As VARCHAR(28)) As co_appl_race, CAST(hm11.co_applicant_ethnicity_name As VARCHAR(28)) As co_appl_ethn, CAST(hm11.applicant_sex_name As VARCHAR(28)) As applic_sex, CAST(hm11.applicant_race_name_1 As VARCHAR(28)) As applic_race, CAST(hm11.applicant_ethnicity_name As VARCHAR(28)) As applic_ethn, CAST(hm11.agency_abbr As VARCHAR(28)) As agency_abbr FROM hm_11_u_raw hm11 ORDER BY random() ) , hmda_2011_union AS ( SELECT hm_a.* FROM(SELECT * FROM hmda_2011_transform WHERE act_outc = 1 ORDER BY random() LIMIT 12500) hm_a UNION ALL SELECT hm_a.* FROM(SELECT * FROM hmda_2011_transform WHERE act_outc = 0 ORDER BY random() LIMIT 12500) hm_a ) SELECT hm11_u.* INTO interim_datasets_v2.hmda11_srandom_bal_25K FROM hmda_2011_union hm11_u ORDER BY random() ; /*--------------------------- end HMDA 2011 ---------------------------*/ /*----------------------------------------------------- HMDA 2012 ----------------------------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda12_srandom_bal_25K ; -- WITH hm_12_ap AS --extract the raw data fields for segment of approved loans with loan type = Conventional ( SELECT hm12.action_taken_name As act, hm12.as_of_year, TRIM(LEADING '0' FROM rate_spread) As rate_spread, hm12.tract_to_msamd_income, hm12.population, hm12.agency_abbr, hm12.minority_population, hm12.number_of_owner_occupied_units, hm12.loan_amount_000s, hm12.number_of_1_to_4_family_units, hm12.hud_median_family_income, hm12.applicant_income_000s, hm12.state_abbr, hm12.property_type_name, hm12.owner_occupancy_name, hm12.msamd_name, hm12.lien_status_name, hm12.hoepa_status_name, hm12.co_applicant_sex_name, hm12.co_applicant_ethnicity_name, hm12.co_applicant_race_name_1, hm12.applicant_sex_name, hm12.applicant_race_name_1, hm12.applicant_ethnicity_name, --set Null because all denial reasons are null for approved loans NULL As denial_reason_name_1, NULL AS denial_reason_name_2, NULL AS denial_reason_name_3 FROM public.hmda_lar_2012_allrecords hm12 WHERE hm12.action_taken_name = 'Loan originated' AND hm12.loan_type_name = 'Conventional' AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm12.as_of_year Is Not NULL AND hm12.tract_to_msamd_income Is Not Null AND hm12.population Is Not Null AND hm12.minority_population Is Not Null AND hm12.number_of_owner_occupied_units Is Not Null AND hm12.hud_median_family_income Is Not Null AND hm12.applicant_income_000s Is Not Null AND hm12.state_abbr Is Not Null AND hm12.property_type_name Is Not Null AND hm12.owner_occupancy_name Is Not Null AND hm12.msamd_name Is Not Null AND hm12.lien_status_name Is Not Null AND hm12.hoepa_status_name Is Not Null AND hm12.co_applicant_sex_name Is Not Null AND hm12.co_applicant_race_name_1 Is Not Null AND hm12.co_applicant_ethnicity_name Is Not Null AND hm12.applicant_sex_name Is Not Null AND hm12.applicant_race_name_1 Is Not Null AND hm12.applicant_ethnicity_name Is Not Null AND hm12.agency_abbr Is Not Null AND hm12.loan_amount_000s Is Not Null AND hm12.rate_spread Is Not Null AND hm12.number_of_1_to_4_family_units Is Not Null AND hm12.rate_spread != '' AND hm12.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm_12_u_raw) ) , hm_12_de AS --extract the raw data fields for segment of denied loans with loan type = Conventional ( SELECT hm12.action_taken_name As act, hm12.as_of_year, NULL as rate_spread, hm12.tract_to_msamd_income, hm12.population, hm12.agency_abbr, hm12.minority_population, hm12.number_of_owner_occupied_units, hm12.loan_amount_000s, hm12.number_of_1_to_4_family_units, hm12.hud_median_family_income, hm12.applicant_income_000s, hm12.state_abbr, hm12.property_type_name, hm12.owner_occupancy_name, hm12.msamd_name, hm12.lien_status_name, hm12.hoepa_status_name, hm12.co_applicant_sex_name, hm12.co_applicant_ethnicity_name, hm12.co_applicant_race_name_1, hm12.applicant_sex_name, hm12.applicant_race_name_1, hm12.applicant_ethnicity_name, --extract all denial reasons to concatenate in the following CTE hm12.denial_reason_name_1, hm12.denial_reason_name_2, hm12.denial_reason_name_3 FROM public.hmda_lar_2012_allrecords hm12 WHERE hm12.action_taken_name = 'Application denied by financial institution' AND hm12.loan_type_name = 'Conventional' AND ( hm12.denial_reason_name_1 Is Not Null Or denial_reason_name_2 Is not Null OR denial_reason_name_3 Is Not Null ) --dropping all missing denied loans without a denial reason AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm12.as_of_year Is Not NULL AND hm12.tract_to_msamd_income Is Not Null AND hm12.population Is Not Null AND hm12.minority_population Is Not Null AND hm12.number_of_owner_occupied_units Is Not Null AND hm12.hud_median_family_income Is Not Null AND hm12.applicant_income_000s Is Not Null AND hm12.state_abbr Is Not Null AND hm12.property_type_name Is Not Null AND hm12.owner_occupancy_name Is Not Null AND hm12.msamd_name Is Not Null AND hm12.lien_status_name Is Not Null AND hm12.hoepa_status_name Is Not Null AND hm12.co_applicant_sex_name Is Not Null AND hm12.co_applicant_race_name_1 Is Not Null AND hm12.co_applicant_ethnicity_name Is Not Null AND hm12.applicant_sex_name Is Not Null AND hm12.applicant_race_name_1 Is Not Null AND hm12.applicant_ethnicity_name Is Not Null AND hm12.agency_abbr Is Not Null AND hm12.loan_amount_000s Is Not Null AND hm12.msamd_name != '' hm12.number_of_1_to_4_family_units Is Not Null ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm12_u_raw) ) , hm_12_u_raw AS --UNION ALL for the two segmented CTEs to get balanced dataset of 25K ( SELECT hm_a.* FROM(SELECT * FROM hm_12_ap ORDER BY random() LIMIT 12500) hm_a UNION ALL --note that we take another random sample of 125000 of each 25K randomized sample segment SELECT hm_d.* FROM(SELECT * FROM hm_12_de ORDER BY random() LIMIT 12500) hm_d ) , hmda_2012_transform As ( SELECT --simple binary assignment of 1 or 0 , bc the WHERE clause in this CTE segments the approved/denied subset CASE WHEN hm12.act = 'Loan originated' THEN 1 ELSE 0 END As act_outc, hm12.as_of_year As action_year, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( hm12.rate_spread As Varchar(5)) As NUMERIC ) As rate_spread, --NB: must be num bc of decimals --concatenating denial reasons into one feature on which we do engineering using python CONCAT_WS(', ', hm12.denial_reason_name_1, hm12.denial_reason_name_2, hm12.denial_reason_name_3) as denials, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( CASE WHEN hm12.tract_to_msamd_income IS NULL THEN NULL ELSE hm12.tract_to_msamd_income END As Varchar(5)) As NUMERIC ) As tract_to_msamd_inc, --NB: must be num bc of dec hm12.population As pop, ROUND(hm12.minority_population, 2) As minority_pop_perc, hm12.number_of_owner_occupied_units As num_owoc_units, hm12.number_of_1_to_4_family_units As num_1to4_fam_units, hm12.loan_amount_000s As ln_amt_000s, hm12.hud_median_family_income As hud_med_fm_inc, --must use embedded functions all-in-one to typecast this as integer because raw data stores it as TEXT CAST( CAST( CASE WHEN hm12.applicant_income_000s IS NULL THEN NULL ELSE hm12.applicant_income_000s END As Varchar(5)) As INT ) As applic_inc_000s, CAST(hm12.state_abbr As VARCHAR(5)) As state_abbr, CAST(hm12.property_type_name As VARCHAR(128) ) As property_type_nm, CAST(hm12.owner_occupancy_name As VARCHAR(128)) As own_occ_nm, CAST(hm12.msamd_name As VARCHAR(128)) As msamd_nm, CAST(hm12.lien_status_name As VARCHAR(56)) As lien_status_nm, CAST(hm12.hoepa_status_name As VARCHAR(56)) As hoep_status_nm, CAST(hm12.co_applicant_sex_name As VARCHAR(28)) As co_appl_sex, CAST(hm12.co_applicant_race_name_1 As VARCHAR(28)) As co_appl_race, CAST(hm12.co_applicant_ethnicity_name As VARCHAR(28)) As co_appl_ethn, CAST(hm12.applicant_sex_name As VARCHAR(28)) As applic_sex, CAST(hm12.applicant_race_name_1 As VARCHAR(28)) As applic_race, CAST(hm12.applicant_ethnicity_name As VARCHAR(28)) As applic_ethn, CAST(hm12.agency_abbr As VARCHAR(28)) As agency_abbr FROM hm_12_u_raw hm12 ORDER BY random() ) , hmda_2012_union AS ( SELECT hm_a.* FROM(SELECT * FROM hmda_2012_transform WHERE act_outc = 1 ORDER BY random() LIMIT 12500) hm_a UNION ALL SELECT hm_a.* FROM(SELECT * FROM hmda_2012_transform WHERE act_outc = 0 ORDER BY random() LIMIT 12500) hm_a ) SELECT hm12_u.* INTO interim_datasets_v2.hmda12_srandom_bal_25K FROM hmda_2012_union hm12_u ORDER BY random() ; /*--------------------------- end HMDA 2012 ---------------------------*/ /*----------------------------------------------------- HMDA 2013 ----------------------------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda13_srandom_bal_25K ; -- WITH hm_13_ap AS --extract the raw data fields for segment of approved loans with loan type = Conventional ( SELECT hm13.action_taken_name As act, hm13.as_of_year, TRIM(LEADING '0' FROM rate_spread) As rate_spread, hm13.tract_to_msamd_income, hm13.population, hm13.agency_abbr, hm13.minority_population, hm13.number_of_owner_occupied_units, hm13.loan_amount_000s, hm13.number_of_1_to_4_family_units, hm13.hud_median_family_income, hm13.applicant_income_000s, hm13.state_abbr, hm13.property_type_name, hm13.owner_occupancy_name, hm13.msamd_name, hm13.lien_status_name, hm13.hoepa_status_name, hm13.co_applicant_sex_name, hm13.co_applicant_ethnicity_name, hm13.co_applicant_race_name_1, hm13.applicant_sex_name, hm13.applicant_race_name_1, hm13.applicant_ethnicity_name, --set Null because all denial reasons are null for approved loans NULL As denial_reason_name_1, NULL AS denial_reason_name_2, NULL AS denial_reason_name_3 FROM public.hmda_lar_2013_allrecords hm13 WHERE hm13.action_taken_name = 'Loan originated' AND hm13.loan_type_name = 'Conventional' AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm13.as_of_year Is Not NULL AND hm13.tract_to_msamd_income Is Not Null AND hm13.population Is Not Null AND hm13.minority_population Is Not Null AND hm13.number_of_owner_occupied_units Is Not Null AND hm13.hud_median_family_income Is Not Null AND hm13.applicant_income_000s Is Not Null AND hm13.state_abbr Is Not Null AND hm13.property_type_name Is Not Null AND hm13.owner_occupancy_name Is Not Null AND hm13.msamd_name Is Not Null AND hm13.lien_status_name Is Not Null AND hm13.hoepa_status_name Is Not Null AND hm13.co_applicant_sex_name Is Not Null AND hm13.co_applicant_race_name_1 Is Not Null AND hm13.co_applicant_ethnicity_name Is Not Null AND hm13.applicant_sex_name Is Not Null AND hm13.applicant_race_name_1 Is Not Null AND hm13.applicant_ethnicity_name Is Not Null AND hm13.agency_abbr Is Not Null AND hm13.loan_amount_000s Is Not Null AND hm13.rate_spread Is Not Null AND hm13.number_of_1_to_4_family_units Is Not Null AND hm13.rate_spread != '' AND hm12.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm_13_u_raw) ) , hm_13_de AS --extract the raw data fields for segment of denied loans with loan type = Conventional ( SELECT hm13.action_taken_name As act, hm13.as_of_year, NULL as rate_spread, hm13.tract_to_msamd_income, hm13.population, hm13.agency_abbr, hm13.minority_population, hm13.number_of_owner_occupied_units, hm13.loan_amount_000s, hm13.number_of_1_to_4_family_units, hm13.hud_median_family_income, hm13.applicant_income_000s, hm13.state_abbr, hm13.property_type_name, hm13.owner_occupancy_name, hm13.msamd_name, hm13.lien_status_name, hm13.hoepa_status_name, hm13.co_applicant_sex_name, hm13.co_applicant_ethnicity_name, hm13.co_applicant_race_name_1, hm13.applicant_sex_name, hm13.applicant_race_name_1, hm13.applicant_ethnicity_name, --extract all denial reasons to concatenate in the following CTE hm13.denial_reason_name_1, hm13.denial_reason_name_2, hm13.denial_reason_name_3 FROM public.hmda_lar_2013_allrecords hm13 WHERE hm13.action_taken_name = 'Application denied by financial institution' AND hm13.loan_type_name = 'Conventional' AND ( hm13.denial_reason_name_1 Is Not Null Or denial_reason_name_2 Is not Null OR denial_reason_name_3 Is Not Null ) --dropping all missing denied loans without a denial reason AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm13.as_of_year Is Not NULL AND hm13.tract_to_msamd_income Is Not Null AND hm13.population Is Not Null AND hm13.minority_population Is Not Null AND hm13.number_of_owner_occupied_units Is Not Null AND hm13.hud_median_family_income Is Not Null AND hm13.applicant_income_000s Is Not Null AND hm13.state_abbr Is Not Null AND hm13.property_type_name Is Not Null AND hm13.owner_occupancy_name Is Not Null AND hm13.msamd_name Is Not Null AND hm13.lien_status_name Is Not Null AND hm13.hoepa_status_name Is Not Null AND hm13.co_applicant_sex_name Is Not Null AND hm13.co_applicant_race_name_1 Is Not Null AND hm13.co_applicant_ethnicity_name Is Not Null AND hm13.applicant_sex_name Is Not Null AND hm13.applicant_race_name_1 Is Not Null AND hm13.applicant_ethnicity_name Is Not Null AND hm13.agency_abbr Is Not Null AND hm13.loan_amount_000s Is Not Null AND hm13.msamd_name != '' AND hm13.number_of_1_to_4_family_units Is Not Null ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm13_u_raw) ) , hm_13_u_raw AS --UNION ALL for the two segmented CTEs to get balanced dataset of 25K ( SELECT hm_a.* FROM(SELECT * FROM hm_13_ap ORDER BY random() LIMIT 12500) hm_a UNION ALL --note that we take another random sample of 125000 of each 25K randomized sample segment SELECT hm_d.* FROM(SELECT * FROM hm_13_de ORDER BY random() LIMIT 12500) hm_d ) , hmda_2013_transform As ( SELECT --simple binary assignment of 1 or 0 , bc the WHERE clause in this CTE segments the approved/denied subset CASE WHEN hm13.act = 'Loan originated' THEN 1 ELSE 0 END As act_outc, hm13.as_of_year As action_year, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( hm13.rate_spread As Varchar(5)) As NUMERIC ) As rate_spread, --NB: must be num bc of decimals --concatenating denial reasons into one feature on which we do engineering using python CONCAT_WS(', ', hm13.denial_reason_name_1, hm13.denial_reason_name_2, hm13.denial_reason_name_3) as denials, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( CASE WHEN hm13.tract_to_msamd_income IS NULL THEN NULL ELSE hm13.tract_to_msamd_income END As Varchar(5)) As NUMERIC ) As tract_to_msamd_inc, --NB: must be num bc of dec hm13.population As pop, ROUND(hm13.minority_population, 2) As minority_pop_perc, hm13.number_of_owner_occupied_units As num_owoc_units, hm13.number_of_1_to_4_family_units As num_1to4_fam_units, hm13.loan_amount_000s As ln_amt_000s, hm13.hud_median_family_income As hud_med_fm_inc, --must use embedded functions all-in-one to typecast this as integer because raw data stores it as TEXT CAST( CAST( CASE WHEN hm13.applicant_income_000s IS NULL THEN NULL ELSE hm13.applicant_income_000s END As Varchar(5)) As INT ) As applic_inc_000s, CAST(hm13.state_abbr As VARCHAR(5)) As state_abbr, CAST(hm13.property_type_name As VARCHAR(128) ) As property_type_nm, CAST(hm13.owner_occupancy_name As VARCHAR(128)) As own_occ_nm, CAST(hm13.msamd_name As VARCHAR(128)) As msamd_nm, CAST(hm13.lien_status_name As VARCHAR(56)) As lien_status_nm, CAST(hm13.hoepa_status_name As VARCHAR(56)) As hoep_status_nm, CAST(hm13.co_applicant_sex_name As VARCHAR(28)) As co_appl_sex, CAST(hm13.co_applicant_race_name_1 As VARCHAR(28)) As co_appl_race, CAST(hm13.co_applicant_ethnicity_name As VARCHAR(28)) As co_appl_ethn, CAST(hm13.applicant_sex_name As VARCHAR(28)) As applic_sex, CAST(hm13.applicant_race_name_1 As VARCHAR(28)) As applic_race, CAST(hm13.applicant_ethnicity_name As VARCHAR(28)) As applic_ethn, CAST(hm13.agency_abbr As VARCHAR(28)) As agency_abbr FROM hm_13_u_raw hm13 ORDER BY random() ) , hmda_2013_union AS ( SELECT hm_a.* FROM(SELECT * FROM hmda_2013_transform WHERE act_outc = 1 ORDER BY random() LIMIT 12500) hm_a UNION ALL SELECT hm_a.* FROM(SELECT * FROM hmda_2013_transform WHERE act_outc = 0 ORDER BY random() LIMIT 12500) hm_a ) SELECT hm13_u.* INTO interim_datasets_v2.hmda13_srandom_bal_25K FROM hmda_2013_union hm13_u ORDER BY random() ; /*--------------------------- end HMDA 2013 ---------------------------*/ /*---------------------------------- Union 2011-2013 ----------------------------------*/ ; WITH hmda_union_2011_to_2013 AS ( SELECT hm11.* FROM interim_datasets_v2.hmda11_srandom_bal_25k hm11 UNION ALL SELECT hm12.* FROM interim_datasets_v2.hmda12_srandom_bal_25K hm12 UNION ALL SELECT hm13.* FROM interim_datasets_v2.hmda13_srandom_bal_25K hm13 ) SELECT hm_u.* INTO interim_datasets_v2.hmda_2011_to_2013_union_srandom_bal_75k FROM hmda_union_2011_to_2013 hm_u ; /*-------------------------------------------------------------------------------------*/ --> END z_tn_AWS_paddleloancanoe <--- --> z_bz_AWS_paddleloancanoe <--- -- CREATE EXTENSION dblink; CREATE SCHEMA raw_datasets ; CREATE ROLE reporting_user WITH LOGIN PASSWORD 'team_loan_canoe2019' ; GRANT USAGE ON SCHEMA raw_datasets TO reporting_user ; GRANT SELECT ON ALL TABLES IN SCHEMA raw_datasets TO reporting_user ; -- /*----------------------------------------------------- HMDA 2014 ----------------------------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda14_srandom_bal_25K ; -- WITH hm_14_ap AS --extract the raw data fields for segment of approved loans with loan type = Conventional ( SELECT hm14.action_taken_name As act, hm14.as_of_year, TRIM(LEADING '0' FROM rate_spread) As rate_spread, hm14.tract_to_msamd_income, hm14.population, hm14.agency_abbr, hm14.minority_population, hm14.number_of_owner_occupied_units, hm14.loan_amount_000s, hm14.number_of_1_to_4_family_units, hm14.hud_median_family_income, hm14.applicant_income_000s, hm14.state_abbr, hm14.property_type_name, hm14.owner_occupancy_name, hm14.msamd_name, hm14.lien_status_name, hm14.hoepa_status_name, hm14.co_applicant_sex_name, hm14.co_applicant_ethnicity_name, hm14.co_applicant_race_name_1, hm14.applicant_sex_name, hm14.applicant_race_name_1, hm14.applicant_ethnicity_name, --set Null because all denial reasons are null for approved loans NULL As denial_reason_name_1, NULL AS denial_reason_name_2, NULL AS denial_reason_name_3 FROM usa_mortgage_market.hmda_lar_2014_allrecords hm14 WHERE hm14.action_taken_name = 'Loan originated' AND hm14.loan_type_name = 'Conventional' AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm14.as_of_year Is Not NULL AND hm14.tract_to_msamd_income Is Not Null AND hm14.population Is Not Null AND hm14.minority_population Is Not Null AND hm14.number_of_owner_occupied_units Is Not Null AND hm14.hud_median_family_income Is Not Null AND hm14.applicant_income_000s Is Not Null AND hm14.state_abbr Is Not Null AND hm14.property_type_name Is Not Null AND hm14.owner_occupancy_name Is Not Null AND hm14.msamd_name Is Not Null AND hm14.lien_status_name Is Not Null AND hm14.hoepa_status_name Is Not Null AND hm14.co_applicant_sex_name Is Not Null AND hm14.co_applicant_race_name_1 Is Not Null AND hm14.co_applicant_ethnicity_name Is Not Null AND hm14.applicant_sex_name Is Not Null AND hm14.applicant_race_name_1 Is Not Null AND hm14.applicant_ethnicity_name Is Not Null AND hm14.agency_abbr Is Not Null AND hm14.loan_amount_000s Is Not Null AND hm14.rate_spread Is Not Null AND hm14.number_of_1_to_4_family_units Is Not Null AND hm14.rate_spread != '' AND hm14.applicant_income_000s != '' AND hm14.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm_14_u_raw) ) , hm_14_de AS --extract the raw data fields for segment of denied loans with loan type = Conventional ( SELECT hm14.action_taken_name As act, hm14.as_of_year, NULL as rate_spread, hm14.tract_to_msamd_income, hm14.population, hm14.agency_abbr, hm14.minority_population, hm14.number_of_owner_occupied_units, hm14.loan_amount_000s, hm14.number_of_1_to_4_family_units, hm14.hud_median_family_income, hm14.applicant_income_000s, hm14.state_abbr, hm14.property_type_name, hm14.owner_occupancy_name, hm14.msamd_name, hm14.lien_status_name, hm14.hoepa_status_name, hm14.co_applicant_sex_name, hm14.co_applicant_ethnicity_name, hm14.co_applicant_race_name_1, hm14.applicant_sex_name, hm14.applicant_race_name_1, hm14.applicant_ethnicity_name, --extract all denial reasons to concatenate in the following CTE hm14.denial_reason_name_1, hm14.denial_reason_name_2, hm14.denial_reason_name_3 FROM usa_mortgage_market.hmda_lar_2014_allrecords hm14 WHERE hm14.action_taken_name = 'Application denied by financial institution' AND hm14.loan_type_name = 'Conventional' AND ( hm14.denial_reason_name_1 Is Not Null Or denial_reason_name_2 Is not Null OR denial_reason_name_3 Is Not Null ) --dropping all missing denied loans without a denial reason AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm14.as_of_year Is Not NULL AND hm14.tract_to_msamd_income Is Not Null AND hm14.population Is Not Null AND hm14.minority_population Is Not Null AND hm14.number_of_owner_occupied_units Is Not Null AND hm14.hud_median_family_income Is Not Null AND hm14.applicant_income_000s Is Not Null AND hm14.state_abbr Is Not Null AND hm14.property_type_name Is Not Null AND hm14.owner_occupancy_name Is Not Null AND hm14.msamd_name Is Not Null AND hm14.lien_status_name Is Not Null AND hm14.hoepa_status_name Is Not Null AND hm14.co_applicant_sex_name Is Not Null AND hm14.co_applicant_race_name_1 Is Not Null AND hm14.co_applicant_ethnicity_name Is Not Null AND hm14.applicant_sex_name Is Not Null AND hm14.applicant_race_name_1 Is Not Null AND hm14.applicant_ethnicity_name Is Not Null AND hm14.agency_abbr Is Not Null AND hm14.loan_amount_000s Is Not Null AND hm14.applicant_income_000s != '' AND hm14.number_of_1_to_4_family_units Is Not Null AND hm14.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm14_u_raw) ) , hm_14_u_raw AS --UNION ALL for the two segmented CTEs to get balanced dataset of 25K ( SELECT hm_a.* FROM(SELECT * FROM hm_14_ap ORDER BY random() LIMIT 12500) hm_a UNION ALL --note that we take another random sample of 125000 of each 25K randomized sample segment SELECT hm_d.* FROM(SELECT * FROM hm_14_de ORDER BY random() LIMIT 12500) hm_d ) , hmda_2014_transform As ( SELECT --simple binary assignment of 1 or 0 , bc the WHERE clause in this CTE segments the approved/denied subset CASE WHEN hm14.act = 'Loan originated' THEN 1 ELSE 0 END As act_outc, hm14.as_of_year As action_year, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( hm14.rate_spread As Varchar(5)) As NUMERIC ) As rate_spread, --NB: must be num bc of decimals --concatenating denial reasons into one feature on which we do engineering using python CONCAT_WS(', ', hm14.denial_reason_name_1, hm14.denial_reason_name_2, hm14.denial_reason_name_3) as denials, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( CASE WHEN hm14.tract_to_msamd_income IS NULL THEN NULL ELSE hm14.tract_to_msamd_income END As Varchar(5)) As NUMERIC ) As tract_to_msamd_inc, --NB: must be num bc of dec hm14.population As pop, ROUND(hm14.minority_population, 2) As minority_pop_perc, hm14.number_of_owner_occupied_units As num_owoc_units, hm14.number_of_1_to_4_family_units As num_1to4_fam_units, hm14.loan_amount_000s As ln_amt_000s, hm14.hud_median_family_income As hud_med_fm_inc, --must use embedded functions all-in-one to typecast this as integer because raw data stores it as TEXT CAST( CAST( CASE WHEN hm14.applicant_income_000s = '' THEN NULL ELSE hm14.applicant_income_000s END As Varchar(5)) As INT ) As applic_inc_000s, CAST(hm14.state_abbr As VARCHAR(5)) As state_abbr, CAST(hm14.property_type_name As VARCHAR(128) ) As property_type_nm, CAST(hm14.owner_occupancy_name As VARCHAR(128)) As own_occ_nm, CAST(hm14.msamd_name As VARCHAR(128)) As msamd_nm, CAST(hm14.lien_status_name As VARCHAR(56)) As lien_status_nm, CAST(hm14.hoepa_status_name As VARCHAR(56)) As hoep_status_nm, CAST(hm14.co_applicant_sex_name As VARCHAR(28)) As co_appl_sex, CAST(hm14.co_applicant_race_name_1 As VARCHAR(28)) As co_appl_race, CAST(hm14.co_applicant_ethnicity_name As VARCHAR(28)) As co_appl_ethn, CAST(hm14.applicant_sex_name As VARCHAR(28)) As applic_sex, CAST(hm14.applicant_race_name_1 As VARCHAR(28)) As applic_race, CAST(hm14.applicant_ethnicity_name As VARCHAR(28)) As applic_ethn, CAST(hm14.agency_abbr As VARCHAR(28)) As agency_abbr FROM hm_14_u_raw hm14 ORDER BY random() ) , hmda_2014_union AS ( SELECT hm_a.* FROM(SELECT * FROM hmda_2014_transform WHERE act_outc = 1 ORDER BY random() LIMIT 12500) hm_a UNION ALL SELECT hm_a.* FROM(SELECT * FROM hmda_2014_transform WHERE act_outc = 0 ORDER BY random() LIMIT 12500) hm_a ) SELECT hm14_u.* INTO interim_datasets_v2.hmda14_srandom_bal_25K FROM hmda_2014_union hm14_u ORDER BY random() ; /*--------------------------- end HMDA 2014 ---------------------------*/ /*----------------------------------------------------- HMDA 2015 ----------------------------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda15_srandom_bal_25K ; -- WITH hm_15_ap AS --extract the raw data fields for segment of approved loans with loan type = Conventional ( SELECT hm15.action_taken_name As act, hm15.as_of_year, TRIM(LEADING '0' FROM rate_spread) As rate_spread, hm15.tract_to_msamd_income, hm15.population, hm15.agency_abbr, hm15.minority_population, hm15.number_of_owner_occupied_units, hm15.loan_amount_000s, hm15.number_of_1_to_4_family_units, hm15.hud_median_family_income, hm15.applicant_income_000s, hm15.state_abbr, hm15.property_type_name, hm15.owner_occupancy_name, hm15.msamd_name, hm15.lien_status_name, hm15.hoepa_status_name, hm15.co_applicant_sex_name, hm15.co_applicant_ethnicity_name, hm15.co_applicant_race_name_1, hm15.applicant_sex_name, hm15.applicant_race_name_1, hm15.applicant_ethnicity_name, --set Null because all denial reasons are null for approved loans NULL As denial_reason_name_1, NULL AS denial_reason_name_2, NULL AS denial_reason_name_3 FROM usa_mortgage_market.hmda_lar_2015_allrecords hm15 WHERE hm15.action_taken_name = 'Loan originated' AND hm15.loan_type_name = 'Conventional' AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm15.as_of_year Is Not NULL AND hm15.tract_to_msamd_income Is Not Null AND hm15.population Is Not Null AND hm15.minority_population Is Not Null AND hm15.number_of_owner_occupied_units Is Not Null AND hm15.hud_median_family_income Is Not Null AND hm15.applicant_income_000s Is Not Null AND hm15.state_abbr Is Not Null AND hm15.property_type_name Is Not Null AND hm15.owner_occupancy_name Is Not Null AND hm15.msamd_name Is Not Null AND hm15.lien_status_name Is Not Null AND hm15.hoepa_status_name Is Not Null AND hm15.co_applicant_sex_name Is Not Null AND hm15.co_applicant_race_name_1 Is Not Null AND hm15.co_applicant_ethnicity_name Is Not Null AND hm15.applicant_sex_name Is Not Null AND hm15.applicant_race_name_1 Is Not Null AND hm15.applicant_ethnicity_name Is Not Null AND hm15.agency_abbr Is Not Null AND hm15.loan_amount_000s Is Not Null AND hm15.rate_spread Is Not Null AND hm15.number_of_1_to_4_family_units Is Not Null AND hm15.rate_spread != '' AND hm15.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm_15_u_raw) ) , hm_15_de AS --extract the raw data fields for segment of denied loans with loan type = Conventional ( SELECT hm15.action_taken_name As act, hm15.as_of_year, NULL as rate_spread, hm15.tract_to_msamd_income, hm15.population, hm15.agency_abbr, hm15.minority_population, hm15.number_of_owner_occupied_units, hm15.loan_amount_000s, hm15.number_of_1_to_4_family_units, hm15.hud_median_family_income, hm15.applicant_income_000s, hm15.state_abbr, hm15.property_type_name, hm15.owner_occupancy_name, hm15.msamd_name, hm15.lien_status_name, hm15.hoepa_status_name, hm15.co_applicant_sex_name, hm15.co_applicant_ethnicity_name, hm15.co_applicant_race_name_1, hm15.applicant_sex_name, hm15.applicant_race_name_1, hm15.applicant_ethnicity_name, --extract all denial reasons to concatenate in the following CTE hm15.denial_reason_name_1, hm15.denial_reason_name_2, hm15.denial_reason_name_3 FROM usa_mortgage_market.hmda_lar_2015_allrecords hm15 WHERE hm15.action_taken_name = 'Application denied by financial institution' AND hm15.loan_type_name = 'Conventional' AND ( hm15.denial_reason_name_1 Is Not Null Or denial_reason_name_2 Is not Null OR denial_reason_name_3 Is Not Null ) --dropping all missing denied loans without a denial reason AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm15.as_of_year Is Not NULL AND hm15.tract_to_msamd_income Is Not Null AND hm15.population Is Not Null AND hm15.minority_population Is Not Null AND hm15.number_of_owner_occupied_units Is Not Null AND hm15.hud_median_family_income Is Not Null AND hm15.applicant_income_000s Is Not Null AND hm15.state_abbr Is Not Null AND hm15.property_type_name Is Not Null AND hm15.owner_occupancy_name Is Not Null AND hm15.msamd_name Is Not Null AND hm15.lien_status_name Is Not Null AND hm15.hoepa_status_name Is Not Null AND hm15.co_applicant_sex_name Is Not Null AND hm15.co_applicant_race_name_1 Is Not Null AND hm15.co_applicant_ethnicity_name Is Not Null AND hm15.applicant_sex_name Is Not Null AND hm15.applicant_race_name_1 Is Not Null AND hm15.applicant_ethnicity_name Is Not Null AND hm15.agency_abbr Is Not Null AND hm15.number_of_1_to_4_family_units Is Not Null AND hm15.loan_amount_000s Is Not Null AND hm15.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm15_u_raw) ) , hm_15_u_raw AS --UNION ALL for the two segmented CTEs to get balanced dataset of 25K ( SELECT hm_a.* FROM(SELECT * FROM hm_15_ap ORDER BY random() LIMIT 12500) hm_a UNION ALL --note that we take another random sample of 125000 of each 25K randomized sample segment SELECT hm_d.* FROM(SELECT * FROM hm_15_de ORDER BY random() LIMIT 12500) hm_d ) , hmda_2015_transform As ( SELECT --simple binary assignment of 1 or 0 , bc the WHERE clause in this CTE segments the approved/denied subset CASE WHEN hm15.act = 'Loan originated' THEN 1 ELSE 0 END As act_outc, hm15.as_of_year As action_year, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( hm15.rate_spread As Varchar(5)) As NUMERIC ) As rate_spread, --NB: must be num bc of decimals --concatenating denial reasons into one feature on which we do engineering using python CONCAT_WS(', ', hm15.denial_reason_name_1, hm15.denial_reason_name_2, hm15.denial_reason_name_3) as denials, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( CASE WHEN hm15.tract_to_msamd_income IS NULL THEN NULL ELSE hm15.tract_to_msamd_income END As Varchar(5)) As NUMERIC ) As tract_to_msamd_inc, --NB: must be num bc of dec hm15.population As pop, ROUND(hm15.minority_population, 2) As minority_pop_perc, hm15.number_of_owner_occupied_units As num_owoc_units, hm15.number_of_1_to_4_family_units As num_1to4_fam_units, hm15.loan_amount_000s As ln_amt_000s, hm15.hud_median_family_income As hud_med_fm_inc, --must use embedded functions all-in-one to typecast this as integer because raw data stores it as TEXT CAST( CAST( CASE WHEN hm15.applicant_income_000s IS NULL THEN NULL ELSE hm15.applicant_income_000s END As Varchar(5)) As INT ) As applic_inc_000s, CAST(hm15.state_abbr As VARCHAR(5)) As state_abbr, CAST(hm15.property_type_name As VARCHAR(128) ) As property_type_nm, CAST(hm15.owner_occupancy_name As VARCHAR(128)) As own_occ_nm, CAST(hm15.msamd_name As VARCHAR(128)) As msamd_nm, CAST(hm15.lien_status_name As VARCHAR(56)) As lien_status_nm, CAST(hm15.hoepa_status_name As VARCHAR(56)) As hoep_status_nm, CAST(hm15.co_applicant_sex_name As VARCHAR(28)) As co_appl_sex, CAST(hm15.co_applicant_race_name_1 As VARCHAR(28)) As co_appl_race, CAST(hm15.co_applicant_ethnicity_name As VARCHAR(28)) As co_appl_ethn, CAST(hm15.applicant_sex_name As VARCHAR(28)) As applic_sex, CAST(hm15.applicant_race_name_1 As VARCHAR(28)) As applic_race, CAST(hm15.applicant_ethnicity_name As VARCHAR(28)) As applic_ethn, CAST(hm15.agency_abbr As VARCHAR(28)) As agency_abbr FROM hm_15_u_raw hm15 ORDER BY random() ) , hmda_2015_union AS ( SELECT hm_a.* FROM(SELECT * FROM hmda_2015_transform WHERE act_outc = 1 ORDER BY random() LIMIT 12500) hm_a UNION ALL SELECT hm_a.* FROM(SELECT * FROM hmda_2015_transform WHERE act_outc = 0 ORDER BY random() LIMIT 12500) hm_a ) SELECT hm15_u.* INTO interim_datasets_v2.hmda15_srandom_bal_25K FROM hmda_2015_union hm15_u ORDER BY random() ; /*--------------------------- end HMDA 2015 ---------------------------*/ /*---------------------------------- Union 2014-2015 ----------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda_2014_2015_union_srandom_bal_50k; ; WITH hmda_union_2014_2015 AS ( SELECT hm14.* FROM interim_datasets_v2.hmda14_srandom_bal_25k hm14 UNION ALL SELECT hm15.* FROM interim_datasets_v2.hmda15_srandom_bal_25K hm15 ) SELECT hm_u.* INTO interim_datasets_v2.hmda_2014_2015_union_srandom_bal_50k FROM hmda_union_2014_2015 hm_u ; /*-------------------------------------------------------------------------------------*/ --> END z_bz_AWS_paddleloancanoe <--- --> z_ak_AWS_paddleloancanoe <--- /*----------------------------------------------------- HMDA 2016 ----------------------------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda16_srandom_bal_25K ; -- WITH hm_16_ap AS --extract the raw data fields for segment of approved loans with loan type = Conventional ( SELECT hm16.action_taken_name As act, hm16.as_of_year, TRIM(LEADING '0' FROM rate_spread) As rate_spread, hm16.tract_to_msamd_income, hm16.population, hm16.agency_abbr, hm16.minority_population, hm16.number_of_owner_occupied_units, hm16.loan_amount_000s, hm16.number_of_1_to_4_family_units, hm16.hud_median_family_income, hm16.applicant_income_000s, hm16.state_abbr, hm16.property_type_name, hm16.owner_occupancy_name, hm16.msamd_name, hm16.lien_status_name, hm16.hoepa_status_name, hm16.co_applicant_sex_name, hm16.co_applicant_ethnicity_name, hm16.co_applicant_race_name_1, hm16.applicant_sex_name, hm16.applicant_race_name_1, hm16.applicant_ethnicity_name, --set Null because all denial reasons are null for approved loans NULL As denial_reason_name_1, NULL AS denial_reason_name_2, NULL AS denial_reason_name_3 FROM public.hmda_lar_2016_allrecords hm16 WHERE hm16.action_taken_name = 'Loan originated' AND hm16.loan_type_name = 'Conventional' AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm16.as_of_year Is Not NULL AND hm16.tract_to_msamd_income Is Not Null AND hm16.population Is Not Null AND hm16.minority_population Is Not Null AND hm16.number_of_owner_occupied_units Is Not Null AND hm16.hud_median_family_income Is Not Null AND hm16.applicant_income_000s Is Not Null AND hm16.state_abbr Is Not Null AND hm16.property_type_name Is Not Null AND hm16.owner_occupancy_name Is Not Null AND hm16.msamd_name Is Not Null AND hm16.lien_status_name Is Not Null AND hm16.hoepa_status_name Is Not Null AND hm16.co_applicant_sex_name Is Not Null AND hm16.co_applicant_race_name_1 Is Not Null AND hm16.co_applicant_ethnicity_name Is Not Null AND hm16.applicant_sex_name Is Not Null AND hm16.applicant_race_name_1 Is Not Null AND hm16.applicant_ethnicity_name Is Not Null AND hm16.agency_abbr Is Not Null AND hm16.loan_amount_000s Is Not Null AND hm16.rate_spread Is Not Null AND hm16.number_of_1_to_4_family_units Is Not Null AND hm16.rate_spread != '' AND hm16.applicant_income_000s != '' AND hm16.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm_16_u_raw) ) , hm_16_de AS --extract the raw data fields for segment of denied loans with loan type = Conventional ( SELECT hm16.action_taken_name As act, hm16.as_of_year, NULL as rate_spread, hm16.tract_to_msamd_income, hm16.population, hm16.agency_abbr, hm16.minority_population, hm16.number_of_owner_occupied_units, hm16.loan_amount_000s, hm16.number_of_1_to_4_family_units, hm16.hud_median_family_income, hm16.applicant_income_000s, hm16.state_abbr, hm16.property_type_name, hm16.owner_occupancy_name, hm16.msamd_name, hm16.lien_status_name, hm16.hoepa_status_name, hm16.co_applicant_sex_name, hm16.co_applicant_ethnicity_name, hm16.co_applicant_race_name_1, hm16.applicant_sex_name, hm16.applicant_race_name_1, hm16.applicant_ethnicity_name, --extract all denial reasons to concatenate in the following CTE hm16.denial_reason_name_1, hm16.denial_reason_name_2, hm16.denial_reason_name_3 FROM public.hmda_lar_2016_allrecords hm16 WHERE hm16.action_taken_name = 'Application denied by financial institution' AND hm16.loan_type_name = 'Conventional' AND ( hm16.denial_reason_name_1 Is Not Null Or denial_reason_name_2 Is not Null OR denial_reason_name_3 Is Not Null ) --dropping all missing denied loans without a denial reason AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm16.as_of_year Is Not NULL AND hm16.tract_to_msamd_income Is Not Null AND hm16.population Is Not Null AND hm16.minority_population Is Not Null AND hm16.number_of_owner_occupied_units Is Not Null AND hm16.hud_median_family_income Is Not Null AND hm16.applicant_income_000s Is Not Null AND hm16.state_abbr Is Not Null AND hm16.property_type_name Is Not Null AND hm16.owner_occupancy_name Is Not Null AND hm16.msamd_name Is Not Null AND hm16.lien_status_name Is Not Null AND hm16.hoepa_status_name Is Not Null AND hm16.co_applicant_sex_name Is Not Null AND hm16.co_applicant_race_name_1 Is Not Null AND hm16.co_applicant_ethnicity_name Is Not Null AND hm16.applicant_sex_name Is Not Null AND hm16.applicant_race_name_1 Is Not Null AND hm16.applicant_ethnicity_name Is Not Null AND hm16.agency_abbr Is Not Null AND hm16.loan_amount_000s Is Not Null AND hm16.applicant_income_000s != '' AND hm16.number_of_1_to_4_family_units Is Not Null AND hm16.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm16_u_raw) ) , hm_16_u_raw AS --UNION ALL for the two segmented CTEs to get balanced dataset of 25K ( SELECT hm_a.* FROM(SELECT * FROM hm_16_ap ORDER BY random() LIMIT 12500) hm_a UNION ALL --note that we take another random sample of 125000 of each 25K randomized sample segment SELECT hm_d.* FROM(SELECT * FROM hm_16_de ORDER BY random() LIMIT 12500) hm_d ) , hmda_2016_transform As ( SELECT --simple binary assignment of 1 or 0 , bc the WHERE clause in this CTE segments the approved/denied subset CASE WHEN hm16.act = 'Loan originated' THEN 1 ELSE 0 END As act_outc, hm16.as_of_year As action_year, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( hm16.rate_spread As Varchar(5)) As NUMERIC ) As rate_spread, --NB: must be num bc of decimals --concatenating denial reasons into one feature on which we do engineering using python CONCAT_WS(', ', hm16.denial_reason_name_1, hm16.denial_reason_name_2, hm16.denial_reason_name_3) as denials, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( CASE WHEN hm16.tract_to_msamd_income IS NULL THEN NULL ELSE hm16.tract_to_msamd_income END As Varchar(5)) As NUMERIC ) As tract_to_msamd_inc, --NB: must be num bc of dec hm16.population As pop, ROUND(hm16.minority_population, 2) As minority_pop_perc, hm16.number_of_owner_occupied_units As num_owoc_units, hm16.number_of_1_to_4_family_units As num_1to4_fam_units, hm16.loan_amount_000s As ln_amt_000s, hm16.hud_median_family_income As hud_med_fm_inc, --must use embedded functions all-in-one to typecast this as integer because raw data stores it as TEXT CAST( CAST( CASE WHEN hm16.applicant_income_000s = '' THEN NULL ELSE hm16.applicant_income_000s END As Varchar(5)) As INT ) As applic_inc_000s, CAST(hm16.state_abbr As VARCHAR(5)) As state_abbr, CAST(hm16.property_type_name As VARCHAR(128) ) As property_type_nm, CAST(hm16.owner_occupancy_name As VARCHAR(128)) As own_occ_nm, CAST(hm16.msamd_name As VARCHAR(128)) As msamd_nm, CAST(hm16.lien_status_name As VARCHAR(56)) As lien_status_nm, CAST(hm16.hoepa_status_name As VARCHAR(56)) As hoep_status_nm, CAST(hm16.co_applicant_sex_name As VARCHAR(28)) As co_appl_sex, CAST(hm16.co_applicant_race_name_1 As VARCHAR(28)) As co_appl_race, CAST(hm16.co_applicant_ethnicity_name As VARCHAR(28)) As co_appl_ethn, CAST(hm16.applicant_sex_name As VARCHAR(28)) As applic_sex, CAST(hm16.applicant_race_name_1 As VARCHAR(28)) As applic_race, CAST(hm16.applicant_ethnicity_name As VARCHAR(28)) As applic_ethn, CAST(hm16.agency_abbr As VARCHAR(28)) As agency_abbr FROM hm_16_u_raw hm16 ORDER BY random() ) , hmda_2016_union AS ( SELECT hm_a.* FROM(SELECT * FROM hmda_2016_transform WHERE act_outc = 1 ORDER BY random() LIMIT 12500) hm_a UNION ALL SELECT hm_a.* FROM(SELECT * FROM hmda_2016_transform WHERE act_outc = 0 ORDER BY random() LIMIT 12500) hm_a ) SELECT hm16_u.* INTO interim_datasets_v2.hmda16_srandom_bal_25K FROM hmda_2016_union hm16_u ORDER BY random() ; /*--------------------------- end HMDA 2016 ---------------------------*/ /*----------------------------------------------------- HMDA 2017 ----------------------------------------------------*/ DROP TABLE IF EXISTS interim_datasets_v2.hmda17_srandom_bal_25K ; -- WITH hm_17_ap AS --extract the raw data fields for segment of approved loans with loan type = Conventional ( SELECT hm17.action_taken_name As act, hm17.as_of_year, TRIM(LEADING '0' FROM rate_spread) As rate_spread, hm17.tract_to_msamd_income, hm17.population, hm17.agency_abbr, hm17.minority_population, hm17.number_of_owner_occupied_units, hm17.loan_amount_000s, hm17.number_of_1_to_4_family_units, hm17.hud_median_family_income, hm17.applicant_income_000s, hm17.state_abbr, hm17.property_type_name, hm17.owner_occupancy_name, hm17.msamd_name, hm17.lien_status_name, hm17.hoepa_status_name, hm17.co_applicant_sex_name, hm17.co_applicant_ethnicity_name, hm17.co_applicant_race_name_1, hm17.applicant_sex_name, hm17.applicant_race_name_1, hm17.applicant_ethnicity_name, --set Null because all denial reasons are null for approved loans NULL As denial_reason_name_1, NULL AS denial_reason_name_2, NULL AS denial_reason_name_3 FROM public.hmda_lar_2017_allrecords hm17 WHERE hm17.action_taken_name = 'Loan originated' AND hm17.loan_type_name = 'Conventional' AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm17.as_of_year Is Not NULL AND hm17.tract_to_msamd_income Is Not Null AND hm17.population Is Not Null AND hm17.minority_population Is Not Null AND hm17.number_of_owner_occupied_units Is Not Null AND hm17.hud_median_family_income Is Not Null AND hm17.applicant_income_000s Is Not Null AND hm17.state_abbr Is Not Null AND hm17.property_type_name Is Not Null AND hm17.owner_occupancy_name Is Not Null AND hm17.msamd_name Is Not Null AND hm17.lien_status_name Is Not Null AND hm17.hoepa_status_name Is Not Null AND hm17.co_applicant_sex_name Is Not Null AND hm17.co_applicant_race_name_1 Is Not Null AND hm17.co_applicant_ethnicity_name Is Not Null AND hm17.applicant_sex_name Is Not Null AND hm17.applicant_race_name_1 Is Not Null AND hm17.applicant_ethnicity_name Is Not Null AND hm17.agency_abbr Is Not Null AND hm17.loan_amount_000s Is Not Null AND hm17.rate_spread Is Not Null AND hm17.number_of_1_to_4_family_units Is Not Null AND hm17.rate_spread != '' AND hm17.applicant_income_000s != '' AND hm17.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm_17_u_raw) ) , hm_17_de AS --extract the raw data fields for segment of denied loans with loan type = Conventional ( SELECT hm17.action_taken_name As act, hm17.as_of_year, NULL as rate_spread, hm17.tract_to_msamd_income, hm17.population, hm17.agency_abbr, hm17.minority_population, hm17.number_of_owner_occupied_units, hm17.loan_amount_000s, hm17.number_of_1_to_4_family_units, hm17.hud_median_family_income, hm17.applicant_income_000s, hm17.state_abbr, hm17.property_type_name, hm17.owner_occupancy_name, hm17.msamd_name, hm17.lien_status_name, hm17.hoepa_status_name, hm17.co_applicant_sex_name, hm17.co_applicant_ethnicity_name, hm17.co_applicant_race_name_1, hm17.applicant_sex_name, hm17.applicant_race_name_1, hm17.applicant_ethnicity_name, --extract all denial reasons to concatenate in the following CTE hm17.denial_reason_name_1, hm17.denial_reason_name_2, hm17.denial_reason_name_3 FROM public.hmda_lar_2017_allrecords hm17 WHERE hm17.action_taken_name = 'Application denied by financial institution' AND hm17.loan_type_name = 'Conventional' AND ( hm17.denial_reason_name_1 Is Not Null Or denial_reason_name_2 Is not Null OR denial_reason_name_3 Is Not Null ) --dropping all missing denied loans without a denial reason AND ( --dropping all missing values from our dataset bc they are not missing in any systemic way hm17.as_of_year Is Not NULL AND hm17.tract_to_msamd_income Is Not Null AND hm17.population Is Not Null AND hm17.minority_population Is Not Null AND hm17.number_of_owner_occupied_units Is Not Null AND hm17.hud_median_family_income Is Not Null AND hm17.applicant_income_000s Is Not Null AND hm17.state_abbr Is Not Null AND hm17.property_type_name Is Not Null AND hm17.owner_occupancy_name Is Not Null AND hm17.msamd_name Is Not Null AND hm17.lien_status_name Is Not Null AND hm17.hoepa_status_name Is Not Null AND hm17.co_applicant_sex_name Is Not Null AND hm17.co_applicant_race_name_1 Is Not Null AND hm17.co_applicant_ethnicity_name Is Not Null AND hm17.applicant_sex_name Is Not Null AND hm17.applicant_race_name_1 Is Not Null AND hm17.applicant_ethnicity_name Is Not Null AND hm17.agency_abbr Is Not Null AND hm17.loan_amount_000s Is Not Null AND hm17.applicant_income_000s != '' AND hm17.number_of_1_to_4_family_units Is Not Null AND hm17.msamd_name != '' ) ORDER BY random() LIMIT 25000 --random sample of 25000, which we then use to take another random sample of 12500 (CTE: hm17_u_raw) ) , hm_17_u_raw AS --UNION ALL for the two segmented CTEs to get balanced dataset of 25K ( SELECT hm_a.* FROM(SELECT * FROM hm_17_ap ORDER BY random() LIMIT 12500) hm_a UNION ALL --note that we take another random sample of 125000 of each 25K randomized sample segment SELECT hm_d.* FROM(SELECT * FROM hm_17_de ORDER BY random() LIMIT 12500) hm_d ) , hmda_2017_transform As ( SELECT --simple binary assignment of 1 or 0 , bc the WHERE clause in this CTE segments the approved/denied subset CASE WHEN hm17.act = 'Loan originated' THEN 1 ELSE 0 END As act_outc, hm17.as_of_year As action_year, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( hm17.rate_spread As Varchar(5)) As NUMERIC ) As rate_spread, --NB: must be num bc of decimals --concatenating denial reasons into one feature on which we do engineering using python CONCAT_WS(', ', hm17.denial_reason_name_1, hm17.denial_reason_name_2, hm17.denial_reason_name_3) as denials, --must use embedded functions to typecast this as integer because of NULL/space characters in raw data CAST( CAST( CASE WHEN hm17.tract_to_msamd_income IS NULL THEN NULL ELSE hm17.tract_to_msamd_income END As Varchar(5)) As NUMERIC ) As tract_to_msamd_inc, --NB: must be num bc of dec hm17.population As pop, ROUND(hm17.minority_population, 2) As minority_pop_perc, hm17.number_of_owner_occupied_units As num_owoc_units, hm17.number_of_1_to_4_family_units As num_1to4_fam_units, hm17.loan_amount_000s As ln_amt_000s, hm17.hud_median_family_income As hud_med_fm_inc, --must use embedded functions all-in-one to typecast this as integer because raw data stores it as TEXT CAST( CAST( CASE WHEN hm17.applicant_income_000s = '' THEN NULL ELSE hm17.applicant_income_000s END As Varchar(5)) As INT ) As applic_inc_000s, CAST(hm17.state_abbr As VARCHAR(5)) As state_abbr, CAST(hm17.property_type_name As VARCHAR(128) ) As property_type_nm, CAST(hm17.owner_occupancy_name As VARCHAR(128)) As own_occ_nm, CAST(hm17.msamd_name As VARCHAR(128)) As msamd_nm, CAST(hm17.lien_status_name As VARCHAR(56)) As lien_status_nm, CAST(hm17.hoepa_status_name As VARCHAR(56)) As hoep_status_nm, CAST(hm17.co_applicant_sex_name As VARCHAR(28)) As co_appl_sex, CAST(hm17.co_applicant_race_name_1 As VARCHAR(28)) As co_appl_race, CAST(hm17.co_applicant_ethnicity_name As VARCHAR(28)) As co_appl_ethn, CAST(hm17.applicant_sex_name As VARCHAR(28)) As applic_sex, CAST(hm17.applicant_race_name_1 As VARCHAR(28)) As applic_race, CAST(hm17.applicant_ethnicity_name As VARCHAR(28)) As applic_ethn, CAST(hm17.agency_abbr As VARCHAR(28)) As agency_abbr FROM hm_17_u_raw hm17 ORDER BY random() ) , hmda_2017_union AS ( SELECT hm_a.* FROM(SELECT * FROM hmda_2017_transform WHERE act_outc = 1 ORDER BY random() LIMIT 12500) hm_a UNION ALL SELECT hm_a.* FROM(SELECT * FROM hmda_2017_transform WHERE act_outc = 0 ORDER BY random() LIMIT 12500) hm_a ) SELECT hm17_u.* INTO interim_datasets_v2.hmda17_srandom_bal_25K FROM hmda_2017_union hm17_u ORDER BY random() ; /*--------------------------- end HMDA 2017 ---------------------------*/ /*---------------------------------- Union 2016-2017 ----------------------------------*/ ; WITH hmda_union_2016_2017 AS ( SELECT hm16.* FROM interim_datasets_v2.hmda16_srandom_bal_25k hm16 UNION ALL SELECT hm17.* FROM interim_datasets_v2.hmda17_srandom_bal_25K hm17 ) SELECT hm_u.* INTO interim_datasets_v2.hmda_2016_2017_union_srandom_bal_50k FROM hmda_union_2016_2017 hm_u ; /*-------------------------------------------------------------------------------------*/ --> END z_ak_AWS_paddleloancanoe <--- /* Lastly, we use pg_catalogue (or dblink_connect across pgsql databases) to ingest the UNION tbls into one pgsql db */ --> hmda 2011-2013 from pgsql AWS RDS "z_tn_AWS_paddleloancanoe" create table interim_datasets.hmda_lar_union_ii_2011_to_2013_simplerand_bal75k ( action_taken integer, action_year integer, tract_to_masamd_income numeric(1000,2), population integer, min_pop_perc numeric(1000,2), num_owoc_units integer, num_1to4_fam_units integer, ln_amt_000s integer, hud_med_fm_inc integer, applic_inc_000s integer, own_occ_nm varchar, ln_type_nm varchar(56), lien_status_nm varchar(56), hoep_status_nm varchar(56), co_appl_sex varchar(28), co_appl_race varchar(28), co_appl_ethn varchar(28), applic_sex varchar(28), applic_race varchar(28), applic_ethn varchar(28), agency_abbr varchar(28) ) ; set search_path = "pg_catalog" ; set search_path = "interim_datasets" ; SELECT CAST(reltuples as INT) as rows FROM pg_catalog.pg_class C LEFT JOIN pg_catalog.pg_namespace N ON (N.oid = C.relnamespace) WHERE (relkind = 'r' OR relkind = 'v') AND nspname LIKE 'interim#_datasets' ESCAPE '#' AND relname LIKE 'hmda#_lar#_union#_ii#_2011#_to#_2013#_simplerand#_bal75k' ESCAPE '#' ; ---> end of hmda 2011-2013 --> hmda 2016-2017 from pgsql AWS RDS "z_ak_AWS_paddleloancanoe" create table interim_datasets.hmda_lar_union_ii_2016_to_2017_simplerand_bal75k ( action_taken integer, action_year integer, tract_to_masamd_income numeric(1000,2), population integer, min_pop_perc numeric(1000,2), num_owoc_units integer, num_1to4_fam_units integer, ln_amt_000s integer, hud_med_fm_inc integer, applic_inc_000s integer, own_occ_nm varchar, ln_type_nm varchar(56), lien_status_nm varchar(56), hoep_status_nm varchar(56), co_appl_sex varchar(28), co_appl_race varchar(28), co_appl_ethn varchar(28), applic_sex varchar(28), applic_race varchar(28), applic_ethn varchar(28), agency_abbr varchar(28) ) ; set search_path = "pg_catalog" ; set search_path = "interim_datasets" ; SELECT CAST(reltuples as INT) as rows FROM pg_catalog.pg_class C LEFT JOIN pg_catalog.pg_namespace N ON (N.oid = C.relnamespace) WHERE (relkind = 'r' OR relkind = 'v') AND nspname LIKE 'interim#_datasets' ESCAPE '#' AND relname LIKE 'hmda#_lar#_union#_ii#_2016#_to#_2017#_simplerand#_bal50k' ESCAPE '#' ; ---> end of hmda 2016-2017 /*------------------------------------------ UNION ALL 2010-2017 ------------------------------------------*/ ; WITH hmda_union_2010_2017 AS ( SELECT hm10.* FROM interim_datasets_v2.hmda10_srandom_bal_25K hm10 UNION ALL SELECT hm11_13.* FROM interim_datasets_v2.hmda_2011_to_2013_union_srandom_bal_75k hm11_13 UNION ALL SELECT hm14_15.* FROM interim_datasets_v2.hmda_2014_2015_union_srandom_bal_50k hm14_15 UNION ALL SELECT hm16_17.* FROM interim_datasets_v2.hmda_2016_2017_union_srandom_bal_50k hm16_17 ) SELECT hm_u.* INTO interim_datasets_v2.interim_hmda_2010_2017_simplerand_balanced200k FROM hmda_union_2010_2017 hm_u ; /*---------------------------------------------------------------------------------------------------------*/ /*----------------*/ /*** =========================================== END 03b - SQL Script ============================================ ***/
true
86dff74b81262e13d7972994a11d12d3d6f4859a
SQL
Andacanaver/books-backend
/migrations/001.do.create_books_table.sql
UTF-8
683
3.640625
4
[]
no_license
CREATE TABLE books ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, book_name TEXT NOT NULL, date_created TIMESTAMP NOT NULL DEFAULT now() ); CREATE TABLE book_content ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, title TEXT NOT NULL, plot TEXT, book_id INTEGER REFERENCES books(id) ON DELETE CASCADE, date_created TIMESTAMP NOT NULL DEFAULT now() ); CREATE TABLE characters ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, character_name TEXT NOT NULL, char_description TEXT, book_content_id INTEGER REFERENCES book_content(id) ON DELETE CASCADE, date_created TIMESTAMP NOT NULL DEFAULT now() );
true
b6abc86cff82d480b16de200ae2a99e8db7e452f
SQL
nigelainscoe/biml-database
/CRM_Database/Logging/Tables/ClientFileProcessing.sql
UTF-8
482
2.765625
3
[ "MIT" ]
permissive
CREATE TABLE Logging.ClientFileProcessing ( ClientFileId INT IDENTITY NOT NULL , FileName NVARCHAR(256) NOT NULL , StagingStarted DATETIME2(0) , RowsStagedCount INT , StagingCompleted DATETIME2(0) , ProductionLoadStarted DATETIME2(0) , RowsLoadedCount INT , RowsRejectedCount INT , ProductionLoadCompleted DATETIME2(0) , CONSTRAINT PK_ClientFileProcessing PRIMARY KEY CLUSTERED ( ClientFileId ) );
true
8518d6218fb97c18899f0a549c7e559039ed47c9
SQL
cordulaflavio/etl_cecampe_ne
/SQL/024_Relacionamento_ideges_ref_2020_com_censo_escolas_2020.sql
UTF-8
4,574
4.0625
4
[]
no_license
-- Tabela da tabela key_ideges_ref2020_censo_escolar_2020 para relacionar ideges ref2020 a censo_escolar_2020_escolas -- ideges --> ano_ref_ideges = 2020 -- olinda_pdde_adesao_atualizacao --> an_exercicio = 2020 -- key_ideges_ref2020_censo_escolar_2020 -- Insere dados de olinda_pdde_adesao_atualizacao -- insere só os cnpj que estão nas duas tabelas! CREATE TABLE key_ideges_ref2020_censo_escolar_2020 as (SELECT nu_cgc_entidade, an_exercicio, co_escola FROM olinda_pdde_adesao_atualizacao WHERE nu_cgc_entidade IN (SELECT distinct pdde.nu_cgc_entidade FROM olinda_pdde_adesao_atualizacao pdde INNER JOIN ideges ON pdde.nu_cgc_entidade = ideges.cnpj AND ideges.ano_ref_ideges = 2020) AND an_exercicio IN (2020)); select count(*) from key_ideges_ref2020_censo_escolar_2020 -- 119641 -- Alterar nome da coluna! ALTER TABLE key_ideges_ref2020_censo_escolar_2020 RENAME COLUMN nu_cgc_entidade TO cnpj; ALTER TABLE key_ideges_ref2020_censo_escolar_2020 RENAME COLUMN an_exercicio TO ano_ref_ideges; -- Aqui são os cnpj que estão na tabela KEY e não estão na tabela ideges. -- Não pode ter em excesso. Tem que ser zero. SELECT distinct pdde.cnpj FROM key_ideges_ref2020_censo_escolar_2020 pdde LEFT JOIN ideges ON pdde.cnpj = ideges.cnpj WHERE ideges.cnpj IS NULL -- Confirmar que não há cnpj nem ano_ref_ideges nem cod_escola NULL select count (distinct cnpj) from key_ideges_ref2020_censo_escolar_2020 where cnpj IS NULL select count (distinct ano_ref_ideges) from key_ideges_ref2020_censo_escolar_2020 where ano_ref_ideges IS NULL select count (distinct co_escola) from key_ideges_ref2020_censo_escolar_2020 where co_escola IS NULL -- Agora tem que ver se ta faltando. -- Tá faltando (130849-115573) = 15276 (8493 do nordeste) -- Esse número tem que ser igual ao da próxima consulta. select count(distinct cnpj) from ideges where ano_ref_ideges = 2020 --130849 select count (distinct cnpj) from key_ideges_ref2020_censo_escolar_2020 --115573 -- cnpj que está em ideges(2020) e nao esta na tabela key_ideges_ref2020_censo_escolar_2020 SELECT distinct ideges.cnpj FROM key_ideges_ref2020_censo_escolar_2020 a RIGHT JOIN ideges ON a.cnpj = ideges.cnpj WHERE a.cnpj IS NULL AND ideges.ano_ref_ideges = 2020 AND ideges.cod_regiao = 2 ---------------------------------------------------------- ---------------- CRIAR RELACIONAMENTO N:N ---------------- ---------------------------------------------------------- ALTER TABLE key_ideges_ref2020_censo_escolar_2020 ADD PRIMARY KEY (cnpj, ano_ref_ideges, co_escola); --Esse relacionameno tem que dar certo de primeira! ALTER TABLE key_ideges_ref2020_censo_escolar_2020 ADD CONSTRAINT fk_cnpj_ideges2020 FOREIGN KEY (cnpj, ano_ref_ideges) REFERENCES ideges (cnpj, ano_ref_ideges); --Pode ter erro de códigos e escolas! ALTER TABLE key_ideges_ref2020_censo_escolar_2020 ADD CONSTRAINT fk_cnpj_escola2020 FOREIGN KEY (co_escola) REFERENCES censo_escolar_2020_escolas (co_entidade); -- ERROR: insert or update on table "key_ideges_ref2020_censo_escolar_2020" violates foreign key constraint "fk_cnpj_escola2020" -- erro na FKEY -- Aqui são os co_escola que estão na tabela KEY e não estão na tabela ideges. -- Não pode ter em excesso. DELETANDO. DELETE FROM key_ideges_ref2020_censo_escolar_2020 WHERE co_escola IN (SELECT distinct pdde.co_escola FROM key_ideges_ref2020_censo_escolar_2020 pdde LEFT JOIN censo_escolar_2020_escolas escola ON pdde.co_escola = escola.co_entidade WHERE escola.co_entidade IS NULL) ALTER TABLE key_ideges_ref2020_censo_escolar_2020 ADD CONSTRAINT fk_cnpj_escola2020 FOREIGN KEY (co_escola) REFERENCES censo_escolar_2020_escolas (co_entidade); ----------------------------------------------------------------------------------------- -- Agora tem que ver se ta faltando. -- Tá faltando (130849-115546) = 14816 (8497 do nordeste) -- Esse número tem que ser igual ao da próxima consulta. select count(distinct cnpj) from ideges where ano_ref_ideges = 2020 --130849 select count (distinct cnpj) from key_ideges_ref2020_censo_escolar_2020 --115546 -- cnpj que está em ideges(2020) e nao esta na tabela key_ideges_ref2020_censo_escolar_2020 select * from ideges where cnpj IN ( SELECT distinct ideges.cnpj FROM key_ideges_ref2020_censo_escolar_2020 a RIGHT JOIN ideges ON a.cnpj = ideges.cnpj WHERE a.cnpj IS NULL AND ideges.ano_ref_ideges = 2020 AND ideges.cod_regiao = 2) AND ano_ref_ideges = 2020 select count(*) from key_ideges_ref2020_censo_escolar_2020--119614
true
83d92268d6836ec625b85ea88be2b11cc86d0864
SQL
bellmit/origin
/family_order/sql/.svn/pristine/83/83d92268d6836ec625b85ea88be2b11cc86d0864.svn-base
UTF-8
691
3.015625
3
[]
no_license
SELECT eparchy_code,city_code,res_type_code,res_kind_code,to_char(sum(sale_num)) sale_num,value_code,stock_id FROM tf_b_cardsale_log WHERE (:RES_TYPE_CODE is null or res_type_code=:RES_TYPE_CODE) AND (:RES_KIND_CODE is null or res_kind_code=:RES_KIND_CODE) AND (:VALUE_CODE is null or value_code=:VALUE_CODE) AND (:CITY_CODE is null or city_code=:CITY_CODE) AND sale_time>=TO_DATE(:SALE_TIME_S, 'YYYY-MM-DD HH24:MI:SS') AND sale_time<=TO_DATE(:SALE_TIME_E, 'YYYY-MM-DD HH24:MI:SS') AND (:STOCK_ID is null or stock_id=:STOCK_ID) AND (:EPARCHY_CODE is null or eparchy_code=:EPARCHY_CODE) GROUP BY eparchy_code,city_code,res_type_code,res_kind_code,value_code,stock_id
true
000f6d22679b24005a713d839cfd324f5949cc6f
SQL
Abraao2501/Exercicios-SQL
/group by.sql
ISO-8859-2
937
3.984375
4
[ "MIT" ]
permissive
--GROUP BY --Group by divide o resultado da pesquisa em grupos SELECT * FROM Sales.SalesOrderDetail SELECT SpecialOfferID, SUM(UnitPrice) AS 'Soma' FROM Sales.SalesOrderDetail GROUP BY SpecialOfferID SELECT ProductID, COUNT(ProductID)AS 'Contagem' FROM Sales.SalesOrderDetail GROUP BY ProductID SELECT FirstName, COUNT(FirstName) AS 'Quantidade' FROM Person.Person GROUP BY FirstName ORDER BY FirstName asc SELECT Color, AVG(ListPrice) AS 'Mdia' FROM Production.Product WHERE color = 'silver' GROUP BY color SELECT MiddleName, COUNT(firstName) AS 'Quantidade' FROM Person.Person GROUP BY MiddleName SELECT ProductID, AVG(OrderQty) as 'media' FROM Sales.SalesOrderDetail GROUP BY ProductID SELECT top 10 productID, SUM(lineTotal) FROM Sales.SalesOrderDetail GROUP BY ProductID ORDER BY SUM(LineTotal) DESC; SELECT ProductID, count(ProductID) AS 'Quantidade', AVG(orderqty) as 'MEDIA' FROM Production.WorkOrder GROUP BY ProductID
true
559ae74def0bd2af89783dc716c9bc6147245f3b
SQL
radtek/OracleScripts
/SQL/TEMP/id6.sql
UTF-8
500
2.75
3
[]
no_license
SQL> SQL> select 'alter index '||owner||'.'||name||' rebuild tablespace '||tablespace_name 2 ||';' 3 from temp_stats, dba_indexes 4 where 5 temp_stats.name = dba_indexes.index_name 6 and 7 (height > 3 8 or 9 del_lf_rows > 10); SQL> SQL> select 'analyze index '||owner||'.'||name||' compute statistics;' 2 from temp_stats, dba_indexes 3 where 4 temp_stats.name = dba_indexes.index_name 5 and 6 (height > 3 7 or 8 del_lf_rows > 10); SQL> SQL> spool off;
true
473cb8e212986ab7c40541e32b299acbdf767275
SQL
ebukaodu/Exercise-4
/books.sql
UTF-8
10,186
3.140625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Sep 25, 2018 at 06:01 PM -- Server version: 10.1.35-MariaDB -- PHP Version: 7.2.9 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 */; -- -- Database: `books` -- -- -------------------------------------------------------- -- -- Table structure for table `books` -- CREATE TABLE `books` ( `id` int(11) NOT NULL, `title` varchar(50) NOT NULL, `author` varchar(50) NOT NULL, `genre` varchar(50) NOT NULL, `height` varchar(50) NOT NULL, `publisher` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `books` -- INSERT INTO `books` (`id`, `title`, `author`, `genre`, `height`, `publisher`) VALUES (1, 'Fundamentals of Wavelets', 'Goswami, Jaideva', 'signal_processing', '251', 'Wiley'), (2, 'Data Smart', 'Foreman, John', 'data_science', '235', 'Wiley'), (3, 'God Created the Integers', 'Hawking, Stephen', 'mathematics', '197', 'Penguin'), (4, 'Superfreakonomics', 'Dubner, Stephen', 'economics', '179', 'HarperCollins'), (5, 'Orientalism', 'Said, Edward', 'history', '197', 'Penguin'), (6, 'Nature of Statistical Learning Theory, The', 'Vapnik, Vladimir', 'data_science', '230', 'Springer'), (7, 'Integration of the Indian States', 'Menon, V P', 'history', '217', 'Orient Blackswan'), (8, 'Drunkard\'s Walk, The', 'Mlodinow, Leonard', 'science', '197', 'Penguin'), (9, 'Image Processing & Mathematical Morphology', 'Shih, Frank', 'signal_processing', '241', 'CRC'), (10, 'How to Think Like Sherlock Holmes', 'Konnikova, Maria', 'psychology', '240', 'Penguin'), (11, 'Data Scientists at Work', 'Sebastian Gutierrez', 'data_science', '230', 'Apress'), (12, 'Slaughterhouse Five', 'Vonnegut, Kurt', 'fiction', '198', 'Random House'), (13, 'Birth of a Theorem', 'Villani, Cedric', 'mathematics', '234', 'Bodley Head'), (14, 'Structure & Interpretation of Computer Programs', 'Sussman, Gerald', 'computer_science', '240', 'MIT Press'), (15, 'Age of Wrath, The', 'Eraly, Abraham', 'history', '238', 'Penguin'), (16, 'Trial, The', 'Kafka, Frank', 'fiction', '198', 'Random House'), (17, 'Statistical Decision Theory\'', 'Pratt, John', 'data_science', '236', 'MIT Press'), (18, 'Data Mining Handbook', 'Nisbet, Robert', 'data_science', '242', 'Apress'), (19, 'New Machiavelli, The', 'Wells, H. G.', 'fiction', '180', 'Penguin'), (20, 'Physics & Philosophy', 'Heisenberg, Werner', 'science', '197', 'Penguin'), (21, 'Making Software', 'Oram, Andy', 'computer_science', '232', 'O\'Reilly'), (22, 'Analysis, Vol I', 'Tao, Terence', 'mathematics', '248', 'HBA'), (23, 'Machine Learning for Hackers', 'Conway, Drew', 'data_science', '233', 'O\'Reilly'), (24, 'Signal and the Noise, The', 'Silver, Nate', 'data_science', '233', 'Penguin'), (25, 'Python for Data Analysis', 'McKinney, Wes', 'data_science', '233', 'O\'Reilly'), (26, 'Introduction to Algorithms', 'Cormen, Thomas', 'computer_science', '234', 'MIT Press'), (27, 'Beautiful and the Damned, The', 'Deb, Siddhartha', 'nonfiction', '198', 'Penguin'), (28, 'Outsider, The', 'Camus, Albert', 'fiction', '198', 'Penguin'), (29, 'Complete Sherlock Holmes, The - Vol I', 'Doyle, Arthur Conan', 'fiction', '176', 'Random House'), (30, 'Complete Sherlock Holmes, The - Vol II', 'Doyle, Arthur Conan', 'fiction', '176', 'Random House'), (31, 'Wealth of Nations, The', 'Smith, Adam', 'economics', '175', 'Random House'), (32, 'Pillars of the Earth, The', 'Follett, Ken', 'fiction', '176', 'Random House'), (33, 'Mein Kampf', 'Hitler, Adolf', 'nonfiction', '212', 'Rupa'), (34, 'Tao of Physics, The', 'Capra, Fritjof', 'science', '179', 'Penguin'), (35, 'Surely You\'re Joking Mr Feynman', 'Feynman, Richard', 'science', '198', 'Random House'), (36, 'Farewell to Arms, A', 'Hemingway, Ernest', 'fiction', '179', 'Rupa'), (37, 'Veteran, The', 'Forsyth, Frederick', 'fiction', '177', 'Transworld'), (38, 'False Impressions', 'Archer, Jeffery', 'fiction', '177', 'Pan'), (39, 'Last Lecture, The', 'Pausch, Randy', 'nonfiction', '197', 'Hyperion'), (40, 'Return of the Primitive', 'Rand, Ayn', 'philosophy', '202', 'Penguin'), (41, 'Jurassic Park', 'Crichton, Michael', 'fiction', '174', 'Random House'), (42, 'Russian Journal, A', 'Steinbeck, John', 'nonfiction', '196', 'Penguin'), (43, 'Tales of Mystery and Imagination', 'Poe, Edgar Allen', 'fiction', '172', 'HarperCollins'), (44, 'Freakonomics', 'Dubner, Stephen', 'economics', '197', 'Penguin'), (45, 'Hidden Connections, The', 'Capra, Fritjof', 'science', '197', 'HarperCollins'), (46, 'Story of Philosophy, The', 'Durant, Will', 'philosophy', '170', 'Pocket'), (47, 'Asami Asami', 'Deshpande, P L', 'fiction', '205', 'Mauj'), (48, 'Journal of a Novel', 'Steinbeck, John', 'fiction', '196', 'Penguin'), (49, 'Once There Was a War', 'Steinbeck, John', 'nonfiction', '196', 'Penguin'), (50, 'Moon is Down, The', 'Steinbeck, John', 'fiction', '196', 'Penguin'), (51, 'Brethren, The', 'Grisham, John', 'fiction', '174', 'Random House'), (52, 'In a Free State', 'Naipaul, V. S.', 'fiction', '196', 'Rupa'), (53, 'Catch 22', 'Heller, Joseph', 'fiction', '178', 'Random House'), (54, 'Complete Mastermind, The', 'BBC', 'nonfiction', '178', 'BBC'), (55, 'Dylan on Dylan', 'Dylan, Bob', 'nonfiction', '197', 'Random House'), (56, 'Soft Computing & Intelligent Systems', 'Gupta, Madan', 'data_science', '242', 'Elsevier'), (57, 'Textbook of Economic Theory', 'Stonier, Alfred', 'economics', '242', 'Pearson'), (58, 'Econometric Analysis', 'Greene, W. H.', 'economics', '242', 'Pearson'), (59, 'Learning OpenCV', 'Bradsky, Gary', 'data_science', '232', 'O\'Reilly'), (60, 'Data Structures Using C & C++', 'Tanenbaum, Andrew', 'computer_science', '235', 'Prentice Hall'), (61, 'Computer Vision, A Modern Approach', 'Forsyth, David', 'data_science', '255', 'Pearson'), (62, 'Principles of Communication Systems', 'Taub, Schilling', 'computer_science', '240', 'TMH'), (63, 'Let Us C', 'Kanetkar, Yashwant', 'computer_science', '213', 'Prentice Hall'), (64, 'Amulet of Samarkand, The', 'Stroud, Jonathan', 'fiction', '179', 'Random House'), (65, 'Crime and Punishment', 'Dostoevsky, Fyodor', 'fiction', '180', 'Penguin'), (66, 'Angels & Demons', 'Brown, Dan', 'fiction', '178', 'Random House'), (67, 'Argumentative Indian, The', 'Sen, Amartya', 'nonfiction', '209', 'Picador'), (68, 'Sea of Poppies', 'Ghosh, Amitav', 'fiction', '197', 'Penguin'), (69, 'Idea of Justice, The', 'Sen, Amartya', 'nonfiction', '212', 'Penguin'), (70, 'Raisin in the Sun, A', 'Hansberry, Lorraine', 'fiction', '175', 'Penguin'), (71, 'All the President\'s Men', 'Woodward, Bob', 'history', '177', 'Random House'), (72, 'Prisoner of Birth, A', 'Archer, Jeffery', 'fiction', '176', 'Pan'), (73, 'Scoop!', 'Nayar, Kuldip', 'history', '216', 'HarperCollins'), (74, 'Ahe Manohar Tari', 'Deshpande, Sunita', 'nonfiction', '213', 'Mauj'), (75, 'Last Mughal, The', 'Dalrymple, William', 'history', '199', 'Penguin'), (76, 'Social Choice & Welfare, Vol 39 No. 1', 'Various', 'economics', '235', 'Springer'), (77, 'Radiowaril Bhashane & Shrutika', 'Deshpande, P L', 'nonfiction', '213', 'Mauj'), (78, 'Gun Gayin Awadi', 'Deshpande, P L', 'nonfiction', '212', 'Mauj'), (79, 'Aghal Paghal', 'Deshpande, P L', 'nonfiction', '212', 'Mauj'), (80, 'Maqta-e-Ghalib', 'Garg, Sanjay', 'fiction', '221', 'Mauj'), (81, 'Beyond Degrees', '', 'nonfiction', '222', 'HarperCollins'), (82, 'Manasa', 'Kale, V P', 'nonfiction', '213', 'Mauj'), (83, 'India from Midnight to Milennium', 'Tharoor, Shashi', 'history', '198', 'Penguin'), (84, 'World\'s Greatest Trials, The', '', 'history', '210', ''), (85, 'Great Indian Novel, The', 'Tharoor, Shashi', 'fiction', '198', 'Penguin'), (86, 'O Jerusalem!', 'Lapierre, Dominique', 'history', '217', 'vikas'), (87, 'City of Joy, The', 'Lapierre, Dominique', 'fiction', '177', 'vikas'), (88, 'Freedom at Midnight', 'Lapierre, Dominique', 'history', '167', 'vikas'), (89, 'Winter of Our Discontent, The', 'Steinbeck, John', 'fiction', '196', 'Penguin'), (90, 'On Education', 'Russell, Bertrand', 'philosophy', '203', 'Routledge'), (91, 'Free Will', 'Harris, Sam', 'philosophy', '203', 'FreePress'), (92, 'Bookless in Baghdad', 'Tharoor, Shashi', 'nonfiction', '206', 'Penguin'), (93, 'Case of the Lame Canary, The', 'Gardner, Earle Stanley', 'fiction', '179', ''), (94, 'Theory of Everything, The', 'Hawking, Stephen', 'science', '217', 'Jaico'), (95, 'New Markets & Other Essays', 'Drucker, Peter', 'economics', '176', 'Penguin'), (96, 'Electric Universe', 'Bodanis, David', 'science', '201', 'Penguin'), (97, 'Hunchback of Notre Dame, The', 'Hugo, Victor', 'fiction', '175', 'Random House'), (98, 'Burning Bright', 'Steinbeck, John', 'fiction', '175', 'Penguin'), (99, 'Age of Discontuinity, The', 'Drucker, Peter', 'economics', '178', 'Random House'), (100, 'Doctor in the Nude', 'Gordon, Richard', 'fiction', '179', 'Penguin'), (101, 'Down and Out in Paris & London', 'Orwell, George', 'nonfiction', '179', 'Penguin'), (102, 'Identity & Violence', 'Sen, Amartya', 'philosophy', '219', 'Penguin'), (103, 'Beyond the Three Seas', 'Dalrymple, William', 'history', '197', 'Random House'), (104, 'World\'s Greatest Short Stories, The', '', 'fiction', '217', 'Jaico'), (105, 'Talking Straight', 'Iacoca, Lee', 'nonfiction', '175', ''), (106, 'Maugham\'s Collected Short Stories, Vol 3', 'Maugham, William S', 'fiction', '171', 'Vintage'), (107, 'Phantom of Manhattan, The', 'Forsyth, Frederick', 'fiction', '180', ''), (108, 'Ashenden of The British Agent', 'Maugham, William S', 'fiction', '160', 'Vintage'), (109, 'Zen & The Art of Motorcycle Maintenance', 'Pirsig, Robert', 'philosophy', '172', 'Vintage'), (110, 'Great War for Civilization, The', 'Fisk, Robert', 'history', '197', 'HarperCollins'), (111, 'We the Living', 'Rand, Ayn', 'fiction', '178', 'Penguin'), (112, 'Artist and the Mathematician, The', 'Aczel, Amir', 'science', '186', 'HighStakes'), (113, 'History of Western Philosophy', 'Russell, Bertrand', 'philosophy', '213', 'Routledge'), (114, 'Selected Short Stories', '', 'fiction', '215', 'Jaico'), (115, 'Rationality & Freedom', 'Sen, Amartya', 'economics', '213', 'Springer'), (116, 'Clash of Civilizations and Remaking of the World O', 'Huntington, Samuel', 'history', '228', 'Simon&Schuster'), (117, 'Uncommon Wisdom', 'Capra, Fritjof', 'nonfiction', '197', 'Fontana'), (118, 'One', 'Bach, Richard', 'nonfiction', '172', 'Dell'); -- -- Indexes for dumped tables -- -- -- Indexes for table `books` -- ALTER TABLE `books` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `books` -- ALTER TABLE `books` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=125; 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
f892712472d24313230b757b89bad879c8bbe27e
SQL
mike14747/express-passport-sessions
/config/schema.sql
UTF-8
1,032
3.40625
3
[]
no_license
DROP DATABASE IF EXISTS testDB; CREATE DATABASE testDB; USE testDB; set foreign_key_checks=0; -- -------------------------------------------------------- CREATE TABLE sessions ( session_id varchar(128) COLLATE utf8mb4_bin NOT NULL, expires int unsigned NOT NULL, data mediumtext COLLATE utf8mb4_bin, PRIMARY KEY (session_id) ); -- -------------------------------------------------------- CREATE TABLE users ( user_id int NOT NULL AUTO_INCREMENT, username varchar(30) NOT NULL UNIQUE, password varchar(128) NOT NULL, email varchar(60) DEFAULT '[email protected]', address varchar(80) DEFAULT '123 Main Street', city varchar(60) DEFAULT 'Somecity', state varchar(30) DEFAULT 'OH', zip varchar(20) DEFAULT '44111', country varchar(30) DEFAULT 'USA', phone varchar(20) DEFAULT '800-555-1212', access_level tinyint UNSIGNED DEFAULT 1, active boolean DEFAULT 1, PRIMARY KEY (user_id) ); -- -------------------------------------------------------- set foreign_key_checks=1;
true
f98d3af3469ab08049f426fe3296597a5cfbd755
SQL
dragonrossa/database_fakultet
/SQLQuery_10052018.sql
WINDOWS-1250
16,786
3.40625
3
[]
no_license
/*komentari u vie redaka*/ --kreiramo bazu koja se zove Prva_baza CREATE DATABASE Prva_baza; -- ulazak/odabir baze USE Prva_baza; --drop database brie bazu DROP DATABASE Prva_baza; CREATE DATABASE Prva_baza; USE MOJA_FIRMA; CREATE TABLE osobe ( OIB char(11), Ime varchar(50), Prezime varchar(100), Godine INT, Telefon varchar(20) ); --DODAJEM POLJE GRAD ALTER TABLE osobe ADD GRAD VARCHAR(50); -- BRISANJE POLJA IZ TABLICE ALTER TABLE osobe DROP COLUMN TELEFON; --PROMJENA POSTOJEEG POLJA ALTER TABLE osobe ALTER COLUMN Godine VARCHAR(3); ---- BAZA ZADATAK_1_1 CREATE DATABASE Zadatak_1_1; USE Zadatak_1_1; -- PRVO KREIRAMO TABLICU ODJELA CREATE TABLE Odjeli ( ifraOdjela CHAR(3) PRIMARY KEY, NazivOdjela VARCHAR(100) UNIQUE NOT NULL, LokacijaOdjela VARCHAR(100) NOT NULL ); -- KREIRAMO ZAPOSLENIKE CREATE TABLE Zaposlenici( ifraZaposlenika INT PRIMARY KEY, ImeZaposlenika VARCHAR(50) NOT NULL, PrezimeZaposlenika VARCHAR(100) NOT NULL, ifraOdjela CHAR(3) REFERENCES Odjeli(ifraOdjela) ); ---KREIRAMO EFOVE CREATE TABLE efovi ( ifraOdjela CHAR(3) REFERENCES Odjeli(ifraOdjela), ifraZaposlenika INT REFERENCES Zaposlenici(ifraZaposlenika), --- definicija primarnog kljua CONSTRAINT efovi_PK PRIMARY KEY (ifraOdjela, ifraZaposlenika) ); CREATE DATABASE Zadatak_1_2; USE Zadatak_1_2; CREATE TABLE Skladino_mjesto ( ifra_skladita INT PRIMARY KEY, Naziv VARCHAR(100) UNIQUE NOT NULL ); CREATE TABLE Proizvod ( ifra_proizvoda INT, Naziv VARCHAR(100) UNIQUE NOT NULL, ifra_skladita INT, CONSTRAINT Proizvod_pk PRIMARY KEY(ifra_proizvoda), CONSTRAINT Proizvod_sklad_fk FOREIGN KEY (ifra_skladita) REFERENCES Skladino_mjesto (ifra_skladita) ); CREATE TABLE Radnik ( ifra_radnika INT PRIMARY KEY, Ime VARCHAR(50) NOT NULL, Prezime VARCHAR(100) NOT NULL, ifra_skladita INT REFERENCES Skladino_mjesto (ifra_skladita) ); CREATE TABLE Voditelji ( ifra_radnika INT REFERENCES Radnik(ifra_radnika), ifra_skladita INT REFERENCES Skladino_mjesto(ifra_skladita), CONSTRAINT Voditelji_PK PRIMARY KEY (ifra_radnika,ifra_skladita) ); CREATE DATABASE EKSPERIMENT; USE EKSPERIMENT; CREATE TABLE PROBA ( broj INT, tekst VARCHAR(50) ); --UMETANJE PODATAKA INSERT INTO PROBA (broj, tekst) VALUES (1, 'JEDAN'); --KOLSKI --UMETANJE VIE REDAKA JEDNOM NAREDBOM INSERT INSERT INTO PROBA (broj, tekst) VALUES (2, 'DVA'), (3, 'TRI'); --SKRAENI OBLIK INSERT INTO PROBA VALUES (4, 'ETIRI'); --JO KRAE, NE POPUNJAVAMO SVA POLJA INSERT INTO PROBA (broj) VALUES (5); --ILI INSERT INTO PROBA (broj,tekst) VALUES (6, NULL); --UMETANJE I IMPLICITNA KONVERZIJA INSERT INTO PROBA (broj, tekst) VALUES (7.5, 'SEDAM I POLA :)'); --->(1 row(s) affected) -- PROVJERA SADRAJA TABLICE SELECT * FROM PROBA; ---AURIRANJE PODATAKA UPDATE PROBA SET tekst = 'PET' WHERE broj = 5; --brisanje podataka DELETE FROM PROBA WHERE Broj= 6; --- zadatak 1.3 USE master; CREATE DATABASE Zadatak_1_3; USE Zadatak_1_3; CREATE TABLE lanovi ( lanski_broj CHAR(10) PRIMARY KEY, Ime VARCHAR(50) NOT NULL, Prezime VARCHAR(100) NOT NULL, Adresa VARCHAR(100) NOT NULL, Telefon VARCHAR(20) NULL, Datum_ulanjenja DATETIME ); CREATE TABLE anr ( ifra_anra CHAR(10) PRIMARY KEY, Naziv VARCHAR(50) NOT NULL, ); DROP TABLE Cjenik; CREATE TABLE Cjenik ( ifra_cjenika INT PRIMARY KEY, Kategorija VARCHAR(50) NOT NULL, Cijena MONEY NOT NULL, ); CREATE TABLE Filmovi( ifra_filma VARCHAR PRIMARY KEY, Naziv VARCHAR(50) NOT NULL, Reiser VARCHAR(50) NOT NULL, Glavni_glumci VARCHAR(200) NOT NULL, Godina_izdanja INT NOT NULL, Koliina_DVD INT NOT NULL, Koliina_VHS INT NOT NULL, Slika_naslovnice IMAGE, ifra_anra CHAR(10) REFERENCES anr(ifra_anra) ); CREATE TABLE Posudba( lanski_broj CHAR(10) REFERENCES lanovi(lanski_broj), ifra_filma VARCHAR REFERENCES Filmovi(ifra_filma), Datum_posudbe DATETIME, Datum_povratka DATETIME, ifra_cjenika INT REFERENCES Cjenik(ifra_cjenika), CONSTRAINT Posudba_FK PRIMARY KEY (lanski_broj, ifra_filma, Datum_posudbe) ); -- umetnuti 3 retka u ANR INSERT INTO anr VALUES ('1', 'Drama'),('2', 'Akcija'),('3', 'KOMEDIJA'); select * from anr USE Fakultet; -- 3.2 SELECT mbrStud, imestud, prezstud, imestud + prezstud AS Ime_prezime FROM stud; -- 3.3 SELECT DISTINCT imestud FROM stud; --3.4 SELECT mbrstud FROM ispit WHERE sifPred=146 AND ocjena >1; -- poloeni ispiti -- 3.5 Select * FROM tablica - * ispisuje sav sadraj SELECT imeNastavnik, prezNastavnik, (koef +0.4)*800 AS Plaa FROM nastavnik; --3.6 SELECT imeNastavnik, prezNastavnik, (koef +0.4)*800 AS Plaa FROM nastavnik WHERE (koef +0.4)*800 < 3500 OR (koef +0.4)*800 > 8000; --3.7, tablica stud i tablica ispit koje su povezane s mbr studenta//aliasi tablice - npr.Stud = S SELECT S.imeStud,S.prezStud FROM stud S, ispit I WHERE S.mbrStud = I.mbrStud AND I.ocjena = 1 AND I.sifPred BETWEEN 220 AND 240; --3.8 SELECT DISTINCT S.imeStud,S.prezStud --student je mogao polagati vie ispita i dobiti vie 3-ki - zato stavljamo DISTINCT FROM stud S, ispit I WHERE S.mbrStud = I.mbrStud AND I.ocjena = 3; --3.9 SELECT P.nazPred FROM pred P LEFT OUTER JOIN ispit I ON P.sifPred = I.sifPred WHERE I.sifPred IS NULL; --3.10 SELECT DISTINCT * --P.nazPred FROM pred P INNER JOIN ispit I ON P.sifPred = I.sifPred; --- ili pisano drugaije SELECT DISTINCT * --P.nazPred FROM pred P , ispit I WHERE P.sifPred = I.sifPred; --3.11 SELECT S.imeStud, S.prezStud FROM stud S --WHERE S.prezStud LIKE 'K%' -- prezime poinje sa K --WHERE S.prezStud LIKE '%K%' WHERE S.imeStud LIKE '[AEIOU]%' -- ime poinje SAMOGLASNIKOM A,E,I,O ili U --3.12 SELECT S.imeStud, S.prezStud FROM stud S WHERE S.imeStud LIKE '[^AEIOU]%' -- ime NE POINJE samoglasnikom A,E,I,O ili U jer smo stavili znak ^ ili ukoliko stavimo NOT LIKE --3.13 SELECT S.imeStud, S.prezStud FROM stud S WHERE S.imeStud LIKE '[^AEIOU]%' --poinje SAMOGLASNIKOM OR S.imeStud LIKE '%[^AEIOU]' -- ili zavrava SAMOGLASNIKOM --3.14 SELECT S.imeStud, S.prezStud FROM stud S WHERE S.imeStud LIKE '%nk%' --sadrava "nk" jedan iza drugoga u IMENU OR S.prezStud LIKE '%nk%' --sadrava "nk" jedan iza drugoga u PREZIMENU --3.15 --STUD(mbrstud), ISPIT(ocijena), PRED (sifpred) SELECT DISTINCT S.imeStud,S.prezStud, I.sifPred, P.nazPred, I.ocjena --nisam pazio na DISTINCT , imamo 3 tablice >> n-1=3-1= min. 2 uvjeta FROM stud S, ispit I, pred P WHERE S.mbrStud = I.mbrStud AND I.sifPred = P.sifPred; --3.16 --STUD (pbrrod), mjesto(pbr, sifzupanija), zupanija -- SELECT DISTINCT S.imeStud,S.prezStud, ZU.sifZupanija, M.pbr, M.sifZupanija --FROM stud S, zupanija ZU, mjesto M --WHERE S.mbrStud = S.prezStud --AND ZU.sifZupanija = M.sifZupanija SELECT S.imeStud, S.prezStud, MR.nazMjesto AS MJESTO_ROENJA, ZR.nazZupanija AS UPANIJA_ROENJA, --STANOVANJE MS.nazMjesto AS MJESTO_STANOVANJA, --//neto nedostaje ZS.nazZupanija AS UPANIJA_STANOVANJA FROM stud S JOIN mjesto MR ON S.pbrRod = MR.pbr JOIN ZUPANIJA ZR ON MR.sifZupanija = ZR.sifZupanija -- 302 -- DODAJEMO PODATKE STANOVANJA JOIN mjesto MS ON MS.pbr = S.pbrStan JOIN zupanija ZS ON ZS.sifZupanija = MS.sifZupanija --3.17 --PRED, ORGJED (sifOrgjed) SELECT P.nazPred, O.nazOrgjed FROM pred P JOIN orgjed O ON P.sifOrgjed = O.sifOrgjed WHERE P.upisanoStud > 20; -- 26 --3.18 -- imena mjesta pojavljuju se samo jedanput - koristimo DISTINCT --STUD, MJESTO (PBRSTAN) - veemo preko PBR stanovanja SELECT DISTINCT M.nazMjesto FROM stud S JOIN mjesto M ON S.pbrStan= M.pbr; -- 29 --3.19 SELECT DISTINCT M.nazMjesto FROM stud S JOIN mjesto M ON S.pbrStan= M.pbr AND S.pbrRod=S.pbrStan; --26 USE Fakultet -- 3.21 -- pred, orgjed, rezervacija SELECT DISTINCT P.nazPred, R.oznDvorana, O.sifOrgjed --DISTINCT prikazuje samo one termine koji su slobodni FROM pred P JOIN rezervacija R ON P.sifPred=r.sifPred JOIN orgjed O ON O.sifOrgjed = P.sifOrgjed; --ili SELECT DISTINCT P.nazPred, R.oznDvorana, O.sifOrgjed FROM pred P, rezervacija R, orgjed O WHERE p.sifPred = R.sifPred AND o.sifOrgjed = P.sifOrgjed; -- 71 je rezultat -- 3.22 --stud, ispit, nastavnik, mjesto (x2) SELECT DISTINCT N.imeNastavnik, N.prezNastavnik, n.sifNastavnik FROM stud S JOIN ispit I ON S.mbrStud = I.mbrStud JOIN nastavnik N ON N.sifNastavnik=I.sifNastavnik JOIN mjesto MN ON MN.pbr=N.pbrStan JOIN mjesto MS ON MS.pbr=S.pbrStan WHERE MN.sifZupanija=ms.sifZupanija; --> 24 je rezultat -- 3.23 --studenti koji studiraju u mjestu <> mjesta roenja --ali su mjesta u istoj upaniji --stud, mjesto SELECT S.* FROM stud S JOIN mjesto MR ON MR.pbr = S.pbrRod --(MR - mjesto roenja, MS - mjesto stanovanja) JOIN mjesto MS ON MS.pbr = S.pbrStan WHERE MR.sifZupanija = MS.sifZupanija AND S.pbrRod <> S.pbrStan; --> rezultat je 3 studenta (Karlo Krsnik, Igor Bogati, Nataa Cerjan) --3.24 --studenti i nastavnici koji imaju ista prezimena SELECT S.imeStud, S.prezStud, N.imeNastavnik, N.prezNastavnik FROM stud S JOIN nastavnik N ON S.prezStud=N.prezNastavnik; -- 20 --3.25 --trebaju nam 3 tablice >> STUD, ISPIT, PREDMET SELECT DISTINCT S.* --Distinct( isti student je mogao ispit pasti vie puta) FROM stud S JOIN ispit I ON s.mbrStud = i.mbrStud JOIN pred P ON p.sifPred=i.sifPred WHERE I.ocjena =1 AND p.nazPred LIKE 'Osnove baza podat%'; -- rezultat je 2 -- ZADATAK KOJI NIJE NAVEDEN U SKRIPTI SQL -- ispisati studente koji nisu polagali niti jedan ispit SELECT S.* FROM stud S LEFT OUTER JOIN ispit I ON s.mbrStud=i.mbrStud WHERE I.mbrStud IS NULL; -- 194 -- ispisati predmete koje nitko nije polagao SELECT P.* FROM ispit I RIGHT OUTER JOIN pred P ON I.sifPred=P.sifPred WHERE I.sifPred IS NULL; -- 116 ------------------------------------------------------------- SELECT P.* FROM ispit I RIGHT OUTER JOIN pred P ON I.sifPred=P.sifPred WHERE I.sifPred IS NULL -- 116 ORDER BY nazPred, sifOrgjed ASC; --ASC / DESC redosljedno 1.nazPred Adapriv..., Alarmni sustavi,Analiza, zatim ide sifOrgjed 100008... --------------------- --ispisati predmete koje nitko nije polagao SELECT P.* INTO PREDMET_KOJI_NISU_POLAGANI --INTO kreira novu tablicu FROM ispit I RIGHT OUTER JOIN pred P ON I.sifPred=P.sifPred WHERE I.sifPred IS NULL -- 4.4 CREATE VIEW Zadatak44 AS SELECT P.nazPred, R.oznDvorana, R.oznVrstaDan, R.sat FROM PRED P JOIN rezervacija R ON P.sifPred = R.sifPred SELECT * FROM Zadatak44; --rjeenje je 89 --4.5 --nastavnici s mjestom u kojem stanuju CREATE VIEW Zadatak45 AS SELECT N.* , M.nazMjesto FROM NASTAVNIK N JOIN MJESTO M ON N.pbrStan = M.pbr; SELECT * FROM Zadatak45; -- rjeenje je 98 --4.6 --podaci o studentima, predmet, ocjenu i podatke o nastavniku koji je ispitivao CREATE VIEW Zadatak46 AS SELECT S.imeStud, S.prezStud, S.mbrStud, i.ocjena, p.nazPred, n.imeNastavnik, n.prezNastavnik FROM stud S JOIN ispit I ON s.mbrStud=i.mbrStud JOIN nastavnik N ON N.sifNastavnik = i.sifNastavnik JOIN pred P ON P.sifPred = I.sifPred; SELECT * FROM Zadatak_46 -- rezultat je 435 --_____________________________________________-- print left ('Marica', 2) print getdate() select rtrim(s.imeStud) + ' ' + rtrim(s.prezStud) AS Ime_prezime from stud s; --5.1 select s.imeStud, s.prezStud, m.nazMjesto from stud S JOIN mjesto M on S.pbrRod = M.pbr ---ime poinje slovom 'F' WHERE LEFT(imestud,1)= 'F'; ---alternativa je LIKE --5.2 select n.imeNastavnik, n.prezNastavnik, m.nazMjesto, SUBSTRING(nazmjesto, 3,1) As Tree_slovo from nastavnik N JOIN mjesto M ON N.pbrStan=M.pbr --(tablicu nastavnik spajamo s tablicom mjeso preko PBR Stanovanja) where SUBSTRING(nazmjesto, 3,1) ='Z' --5.3 select N.imeNastavnik, N.prezNastavnik, s.imeStud, S.prezStud from nastavnik N JOIN stud S ON SUBSTRING(imeStud,5,1) = SUBSTRING(imenastavnik,5,1) --duljina imena mora biti barem 5 znakova WHERE LEN(imenastavnik) >=5 AND LEN(imestud) >=5 --rezultat 1723 --5.4 -- naziv upanije >13 i manje <20 SELECT Z.*, LEN(nazZupanija) AS Duljina_naziva FROM zupanija Z WHERE LEN(nazZupanija) > 13 and LEN(nazZupanija) < 20 --rezultat je 8 --------------------------- USE fakultet; --17. ispiite imena i prezimena nastavnika s nazivom mjesta u kojem stanuju. SELECT N.imeNastavnik, N.prezNastavnik, M.nazMjesto FROM nastavnik N JOIN mjesto M ON N.pbrStan = M.pbr; --rezultat je 98 --18. ispiimo imena i prezimena svih studenata zajedno s ispitima na koje su izali --i ocijenama koje su dobili. Naravno, biti e studenata koji nisu ni jednom izali na neki ispit --pa kod njih ne moemo ispisati ifru ispita. SELECT DISTINCT S.imeStud, S.prezStud, I.sifPred, I.sifNastavnik, I.ocjena, I.datIspit FROM stud S LEFT OUTER JOIN ispit I ON S.mbrStud=I.mbrStud; --- rezultat 628 --19. Ispiimo sve predmete i dvorane u kojima se predaje. --Kako se neki predmeti ne predaju ovaj semestar, oni nemaju rezerviranu dvoranu --pa e to biti reprezentirano NULL vrijednostima SELECT * FROM pred P LEFT OUTER JOIN rezervacija R ON P.sifPred=R.sifPred ORDER BY P.sifPred, R.oznDvorana, r.oznDvorana, r.oznVrstaDan, R.sat; --20.Ispiimo sve studente koji su izali na ispite i sve predmete. --Naravno, biti e studenata koji nisu izali ni na jedan predmet, ali --isto tako biti e predmeta na koje nitko nije izaao. SELECT * FROM stud S LEFT OUTER JOIN ispit I ON S.mbrStud=I.mbrStud FULL OUTER JOIN pred P ON I.sifPred=P.sifPred; -->Mario says 628, meni ispadne 745 --21. Ispiite sve organizacijske jedinice s pripadajuim nadreenim organizacijskim jedinicama SELECT O.*, N.nazOrgjed AS Nadreena FROM orgjed O LEFT OUTER JOIN orgjed N ON O.sifNadorgjed=N.sifOrgjed --134 --22. Ispiite inicijal imena i prezimena studenta (npr.An. Mili) u jednom stupcu nazvanom Student SELECT LEFT(S.IMESTUD,2) + '.' + RTRIM(S.prezStud) AS INICIJAL FROM stud S -- Iz tablice Studenti ispiite reenice oblika: --Sanja Tarak ima matini broj 2. //CAST i CONVERT f-je mogu povezati CHAR i INT SELECT RTRIM(S.imeStud) + ' ' + RTRIM(S.prezStud) + 'ima matini broj' + CAST(mbrStud AS varchar(10)) FROM stud S --> rezultat je 303 --Izraunajte koliko je dana ostalo do Nove godine. PRINT DATEDIFF(d,getdate(), '2018.12.31') --> rjeenje je 235 (danas je 10.05.2018.) PRINT '2018.12.31'-getdate() --> rjeenje je Aug 23 1900 5:04 AM (sada je 10.05.2018. 18:55h - SQL rauna razliku datuma, poput Excela) --Ispis svih podataka studenata koji su roeni izmeu 1.5. i 1.9.1985. i --ime im zavrava slovom 'A' ili slovom 'J' ili slovom 'R'. SELECT * FROM stud S WHERE datRodStud BETWEEN '1985.5.1' AND '1985.9.1' AND RIGHT(RTRIM(imeStud),1) IN ('A','J','R'); --> rezultat je 35 -------------------------------------- --2. PARCIJALNI ISPIT - SQL-- -------------------------------------- CREATE DATABASE Mihael USE Mihael CREATE TABLE Prijatelji ( ifra_prijatelj CHAR(3) PRIMARY KEY, Ime VARCHAR(25) NOT NULL, Prezime VARCHAR(25) NOT NULL ); CREATE TABLE Medij( ifra_medija CHAR(10) PRIMARY KEY, Naziv_medija VARCHAR(50), Posudba DATETIME ); CREATE TABLE Posudba( ifra CHAR(3) REFERENCES Prijatelji(ifra_prijatelj), ifra_medija CHAR(10) REFERENCES Medij(ifra_medija), Datum_posudbe DATETIME, Datum_povratka DATETIME ); -- Svaku tablicu popunite sa po 3 zapisa (unesite 3 svoja prijatelja i 3 glazbena CD-a koja imate kod kue, -- te proizvoljno unesite ta je koji prijatelj posudio, datum kada je posudio -- i unesite datum kada je vratio samo za jednog prijatelja). INSERT INTO Prijatelji VALUES ('001','Nevenko','Pavlic'), ('002','Zvonimir', 'Ivkovi'), ('003','Kreimir', 'Horvath'); select * from Prijatelji INSERT INTO Medij (ifra_medija, Naziv_medija) VALUES ('AA','ABBA'), ('BB','ROLLING STONES'), ('CC','LAST ACTION HERO'); select * from Medij --DATE - format YYYY-MM-DD SELECT * FROM Medij SELECT * FROM Posudba SELECT * FROM Posudba POS JOIN Prijatelji P on P.ifra=POS.Posudba SELECT * datediff(d, dat.pos, getdate())
true
f84dc85dd78014d7c50fe88ae79fc7966e9598ea
SQL
Zhenghao-Liu/LeetCode_problem-and-solution
/1174.即时食物配送II/solution2.sql
UTF-8
284
3.65625
4
[]
no_license
# Write your MySQL query statement below SELECT ROUND(AVG(IF(order_date=customer_pref_delivery_date,1,0))*100,2) AS immediate_percentage FROM Delivery WHERE (customer_id,order_date) IN (SELECT customer_id,MIN(order_date) AS order_date FROM Delivery GROUP BY customer_id);
true
bf3e564b46b9039aafb11da225e2362427ae7a69
SQL
gabaghul/URI
/2988.sql
UTF-8
1,068
3.578125
4
[]
no_license
select t.name, count(*) as matches, count(case when ((t.id = m.team_1 and m.team_1_goals > m.team_2_goals) or (t.id = m.team_2 and m.team_2_goals > m.team_1_goals)) then m.id end) as "victories", count(case when ((t.id = m.team_1 and m.team_1_goals < m.team_2_goals) or (t.id = m.team_2 and m.team_2_goals < m.team_1_goals)) then m.id end) as "defeats", count(case when ((t.id = m.team_1 and m.team_1_goals = m.team_2_goals) or (t.id = m.team_2 and m.team_2_goals = m.team_1_goals)) then m.id end) as "draws", ((count(case when ((t.id = m.team_1 and m.team_1_goals > m.team_2_goals) or (t.id = m.team_2 and m.team_2_goals > m.team_1_goals)) then m.id end) * 3) + count(case when ((t.id = m.team_1 and m.team_1_goals = m.team_2_goals) or (t.id = m.team_2 and m.team_2_goals = m.team_1_goals)) then m.id end)) as "score" from teams t inner join matches m on (t.id = m.team_1 or t.id = m.team_2) group by t.name order by "score" DESC;
true
dd56139e20db9b0ef0973719c2a0195833ea3d26
SQL
dougfii/zjslzj.web
/db/zjslzj.alter.20180520.sql
UTF-8
29,448
3.078125
3
[]
no_license
alter table t_project add column type INTEGER NOT NULL DEFAULT 0; update t_project set type=1; alter table t_project add column n10005 INTEGER NOT NULL DEFAULT 0; alter table t_project add column n10006 INTEGER NOT NULL DEFAULT 0; alter table t_project add column n10007 INTEGER NOT NULL DEFAULT 0; alter table t_project add column n10008 INTEGER NOT NULL DEFAULT 0; alter table t_project add column n10009 INTEGER NOT NULL DEFAULT 0; alter table t_project add column n10010 INTEGER NOT NULL DEFAULT 0; alter table t_project add column s10005 INTEGER NOT NULL DEFAULT 0; alter table t_project add column s10006 INTEGER NOT NULL DEFAULT 0; alter table t_project add column s10007 INTEGER NOT NULL DEFAULT 0; alter table t_project add column s10008 INTEGER NOT NULL DEFAULT 0; alter table t_project add column s10009 INTEGER NOT NULL DEFAULT 0; alter table t_project add column s10010 INTEGER NOT NULL DEFAULT 0; alter table t_project add column n77 INTEGER NOT NULL DEFAULT 0; alter table t_project add column s77 INTEGER NOT NULL DEFAULT 0; alter table t_project add column n37 INTEGER NOT NULL DEFAULT 0; alter table t_project add column s37 INTEGER NOT NULL DEFAULT 0; alter table t_reply10001 add column t1 TEXT DEFAULT ''; alter table t_reply10001 add column t2 TEXT DEFAULT ''; alter table t_reply10001 add column t3 TEXT DEFAULT ''; alter table t_reply10001 add column t4 TEXT DEFAULT ''; alter table t_reply10001 add column t5 TEXT DEFAULT ''; alter table t_reply10001 add column t6 TEXT DEFAULT ''; -- ----------------------------------------------------- -- Table t_flow77 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow77 CASCADE; CREATE SEQUENCE seq_flow77; DROP TABLE IF EXISTS t_flow77 CASCADE; CREATE TABLE t_flow77 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow77') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id no TEXT DEFAULT '' , -- 编号 signer TEXT DEFAULT '' , -- 签发者, 3:核定人 date TEXT DEFAULT '' , -- 日期 content TEXT DEFAULT '' , -- 内容, 3:核定意见 keywords TEXT DEFAULT '' , -- 关键词 attachments TEXT DEFAULT '' , -- 附件列表 uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_reply77 工作流批复 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_reply77 CASCADE; CREATE SEQUENCE seq_reply77; DROP TABLE IF EXISTS t_reply77 CASCADE; CREATE TABLE t_reply77 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_reply77') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id fid BIGINT NOT NULL DEFAULT 0 , -- flow id no TEXT DEFAULT '' , -- 编号 date TEXT DEFAULT '' , -- 日期 content TEXT DEFAULT '' , -- 批复 uid BIGINT NOT NULL DEFAULT 0 , -- 审批者 act BOOLEAN NOT NULL DEFAULT false , -- 审批状态 del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10001 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10001 CASCADE; CREATE SEQUENCE seq_flow10001; DROP TABLE IF EXISTS t_flow10001 CASCADE; CREATE TABLE t_flow10001 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10001') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10002 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10002 CASCADE; CREATE SEQUENCE seq_flow10002; DROP TABLE IF EXISTS t_flow10002 CASCADE; CREATE TABLE t_flow10002 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10002') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10003 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10003 CASCADE; CREATE SEQUENCE seq_flow10003; DROP TABLE IF EXISTS t_flow10003 CASCADE; CREATE TABLE t_flow10003 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10003') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , t40 TEXT DEFAULT '' , t41 TEXT DEFAULT '' , t42 TEXT DEFAULT '' , t43 TEXT DEFAULT '' , t44 TEXT DEFAULT '' , t45 TEXT DEFAULT '' , t46 TEXT DEFAULT '' , t47 TEXT DEFAULT '' , t48 TEXT DEFAULT '' , t49 TEXT DEFAULT '' , t50 TEXT DEFAULT '' , t51 TEXT DEFAULT '' , t52 TEXT DEFAULT '' , t53 TEXT DEFAULT '' , t54 TEXT DEFAULT '' , t55 TEXT DEFAULT '' , t56 TEXT DEFAULT '' , t57 TEXT DEFAULT '' , t58 TEXT DEFAULT '' , t59 TEXT DEFAULT '' , t60 TEXT DEFAULT '' , t61 TEXT DEFAULT '' , t62 TEXT DEFAULT '' , t63 TEXT DEFAULT '' , t64 TEXT DEFAULT '' , t65 TEXT DEFAULT '' , t66 TEXT DEFAULT '' , t67 TEXT DEFAULT '' , t68 TEXT DEFAULT '' , t69 TEXT DEFAULT '' , t70 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10004 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10004 CASCADE; CREATE SEQUENCE seq_flow10004; DROP TABLE IF EXISTS t_flow10004 CASCADE; CREATE TABLE t_flow10004 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10004') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10005 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10005 CASCADE; CREATE SEQUENCE seq_flow10005; DROP TABLE IF EXISTS t_flow10005 CASCADE; CREATE TABLE t_flow10005 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10005') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10006 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10006 CASCADE; CREATE SEQUENCE seq_flow10006; DROP TABLE IF EXISTS t_flow10006 CASCADE; CREATE TABLE t_flow10006 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10006') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10007 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10007 CASCADE; CREATE SEQUENCE seq_flow10007; DROP TABLE IF EXISTS t_flow10007 CASCADE; CREATE TABLE t_flow10007 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10007') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10008 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10008 CASCADE; CREATE SEQUENCE seq_flow10008; DROP TABLE IF EXISTS t_flow10008 CASCADE; CREATE TABLE t_flow10008 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10008') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10009 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10009 CASCADE; CREATE SEQUENCE seq_flow10009; DROP TABLE IF EXISTS t_flow10009 CASCADE; CREATE TABLE t_flow10009 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10009') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_flow10010 工作流文档 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_flow10010 CASCADE; CREATE SEQUENCE seq_flow10010; DROP TABLE IF EXISTS t_flow10010 CASCADE; CREATE TABLE t_flow10010 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_flow10010') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id name TEXT DEFAULT '' , -- 工程名称 t1 TEXT DEFAULT '' , t2 TEXT DEFAULT '' , t3 TEXT DEFAULT '' , t4 TEXT DEFAULT '' , t5 TEXT DEFAULT '' , t6 TEXT DEFAULT '' , t7 TEXT DEFAULT '' , t8 TEXT DEFAULT '' , t9 TEXT DEFAULT '' , t10 TEXT DEFAULT '' , t11 TEXT DEFAULT '' , t12 TEXT DEFAULT '' , t13 TEXT DEFAULT '' , t14 TEXT DEFAULT '' , t15 TEXT DEFAULT '' , t16 TEXT DEFAULT '' , t17 TEXT DEFAULT '' , t18 TEXT DEFAULT '' , t19 TEXT DEFAULT '' , t20 TEXT DEFAULT '' , t21 TEXT DEFAULT '' , t22 TEXT DEFAULT '' , t23 TEXT DEFAULT '' , t24 TEXT DEFAULT '' , t25 TEXT DEFAULT '' , t26 TEXT DEFAULT '' , t27 TEXT DEFAULT '' , t28 TEXT DEFAULT '' , t29 TEXT DEFAULT '' , t30 TEXT DEFAULT '' , t31 TEXT DEFAULT '' , t32 TEXT DEFAULT '' , t33 TEXT DEFAULT '' , t34 TEXT DEFAULT '' , t35 TEXT DEFAULT '' , t36 TEXT DEFAULT '' , t37 TEXT DEFAULT '' , t38 TEXT DEFAULT '' , t39 TEXT DEFAULT '' , uid BIGINT NOT NULL DEFAULT 0 , -- 最后审批者 replytime TIMESTAMP(0) DEFAULT NULL , -- 最后审批时间 replyid BIGINT NOT NULL DEFAULT 0 , -- 批复回应ID last TIMESTAMP(0) DEFAULT NULL , -- 最后修改 act BOOLEAN NOT NULL DEFAULT false , del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_reply10005 工作流批复 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_reply10005 CASCADE; CREATE SEQUENCE seq_reply10005; DROP TABLE IF EXISTS t_reply10005 CASCADE; CREATE TABLE t_reply10005 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_reply10005') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id fid BIGINT NOT NULL DEFAULT 0 , -- flow id no TEXT DEFAULT '' , -- 编号 date TEXT DEFAULT '' , -- 日期 content TEXT DEFAULT '' , -- 批复 uid BIGINT NOT NULL DEFAULT 0 , -- 审批者 act BOOLEAN NOT NULL DEFAULT false , -- 审批状态 del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_reply10006 工作流批复 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_reply10006 CASCADE; CREATE SEQUENCE seq_reply10006; DROP TABLE IF EXISTS t_reply10006 CASCADE; CREATE TABLE t_reply10006 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_reply10006') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id fid BIGINT NOT NULL DEFAULT 0 , -- flow id no TEXT DEFAULT '' , -- 编号 date TEXT DEFAULT '' , -- 日期 content TEXT DEFAULT '' , -- 批复 uid BIGINT NOT NULL DEFAULT 0 , -- 审批者 act BOOLEAN NOT NULL DEFAULT false , -- 审批状态 del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_reply10007 工作流批复 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_reply10007 CASCADE; CREATE SEQUENCE seq_reply10007; DROP TABLE IF EXISTS t_reply10007 CASCADE; CREATE TABLE t_reply10007 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_reply10007') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id fid BIGINT NOT NULL DEFAULT 0 , -- flow id no TEXT DEFAULT '' , -- 编号 date TEXT DEFAULT '' , -- 日期 content TEXT DEFAULT '' , -- 批复 uid BIGINT NOT NULL DEFAULT 0 , -- 审批者 act BOOLEAN NOT NULL DEFAULT false , -- 审批状态 del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_reply10008 工作流批复 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_reply10008 CASCADE; CREATE SEQUENCE seq_reply10008; DROP TABLE IF EXISTS t_reply10008 CASCADE; CREATE TABLE t_reply10008 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_reply10008') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id fid BIGINT NOT NULL DEFAULT 0 , -- flow id no TEXT DEFAULT '' , -- 编号 date TEXT DEFAULT '' , -- 日期 content TEXT DEFAULT '' , -- 批复 uid BIGINT NOT NULL DEFAULT 0 , -- 审批者 act BOOLEAN NOT NULL DEFAULT false , -- 审批状态 del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_reply10009 工作流批复 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_reply10009 CASCADE; CREATE SEQUENCE seq_reply10009; DROP TABLE IF EXISTS t_reply10009 CASCADE; CREATE TABLE t_reply10009 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_reply10009') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id fid BIGINT NOT NULL DEFAULT 0 , -- flow id no TEXT DEFAULT '' , -- 编号 date TEXT DEFAULT '' , -- 日期 content TEXT DEFAULT '' , -- 批复 uid BIGINT NOT NULL DEFAULT 0 , -- 审批者 act BOOLEAN NOT NULL DEFAULT false , -- 审批状态 del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) ); -- ----------------------------------------------------- -- Table t_reply10010 工作流批复 -- ----------------------------------------------------- DROP SEQUENCE IF EXISTS seq_reply10010 CASCADE; CREATE SEQUENCE seq_reply10010; DROP TABLE IF EXISTS t_reply10010 CASCADE; CREATE TABLE t_reply10010 ( id BIGINT UNIQUE DEFAULT NEXTVAL('seq_reply10010') NOT NULL , pid BIGINT NOT NULL DEFAULT 0 , -- project id fid BIGINT NOT NULL DEFAULT 0 , -- flow id no TEXT DEFAULT '' , -- 编号 date TEXT DEFAULT '' , -- 日期 content TEXT DEFAULT '' , -- 批复 uid BIGINT NOT NULL DEFAULT 0 , -- 审批者 act BOOLEAN NOT NULL DEFAULT false , -- 审批状态 del BOOLEAN NOT NULL DEFAULT false , time TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (id) );
true
012d2bde92c00d64bc08affd3b8357fa54aae60b
SQL
hw79chopin/MySQL-Codebook
/SQL 스터디/초급/052.sql
UTF-8
277
3.359375
3
[]
no_license
-- 집계 결과 출력하기 (ROLLUP) (MySQL에서는 WITH ROLLUP) -- Q 부번호, 직업과 직업별 토탈 월급을 출력하되, 중간중간마다 부서의 토탈 월급을 출력하시오 SELECT deptno, job, sum(sal) FROM emp GROUP BY deptno, job WITH ROLLUP;
true
46887bd2c8b240cd9cc4c2113a46388ea4b2be27
SQL
jimianelli/FishSampleR
/cases/Atka/sql/atka.sql
UTF-8
979
3.125
3
[]
no_license
/* age script for revised aug 98 */ spool atka_age.dat set pagesize 0; set linesize 65; set termout off; set feedback off; select h.vessel_type ||'_'||h.cruise||'_'||h.vessel||'_'||h.haul||' '|| h.nmfs_area ||' '|| nvl(h.bottom_depth,-9) ||' '|| to_char(x.haul_date,'mm') ||' '|| to_char(x.haul_date,'dd') ||' '|| to_char(x.haul_date,'yy') ||' '|| h.latitude ||' '|| h.longitude ||' '|| NVL(x.age,-9) ||' '|| DECODE(x.sex,'M',1,'F',2, 'U',3,null)||' '|| x.species ||' '|| NVL(x.weight,-9) ||' '|| x.length ||' '|| x.specimen_number ||' '|| x.sampling_system from norpac.domestic_haul h, norpac.domestic_age x where /*join between domestic_age and domestic_hauls*/ h.haul_join=x.haul_join and /*user specifications*/ x.species = 204 and h.nmfs_area between 500 and 544 ; spool off;
true
78c175e3530094069ca3669b2d3a4eea5d5fac24
SQL
malliina/musicpimp
/musicpimp/conf/db/migration/V1__initial.sql
UTF-8
2,553
3.765625
4
[ "BSD-3-Clause" ]
permissive
create table if not exists USERS ( USER varchar(100) not null primary key, PASS_HASH text not null ); create table if not exists FOLDERS ( ID varchar(191) not null primary key, TITLE text not null, PATH text not null, PARENT varchar(191) not null, constraint FOLDERS_PARENT_FK foreign key (PARENT) references FOLDERS (ID) on update cascade on delete cascade ); create table if not exists TRACKS ( ID varchar(191) not null primary key, TITLE text not null, ARTIST text not null, ALBUM text not null, DURATION int not null, SIZE bigint not null, PATH varchar(254) default '' not null, FOLDER varchar(191) not null, constraint TRACKS_FOLDER_FK foreign key (FOLDER) references FOLDERS (ID) on update cascade on delete cascade ); create table if not exists TOKENS ( USER varchar(100) not null, SERIES bigint not null, TOKEN bigint not null, constraint TOKENS_USER_FK foreign key (USER) references USERS (USER) on update cascade on delete cascade ); create table if not exists TEMP_TRACKS ( ID varchar(191) not null primary key ); create table if not exists TEMP_FOLDERS ( ID varchar(191) not null primary key ); create table if not exists PLAYS ( TRACK varchar(191) not null, `WHEN` timestamp(3) default CURRENT_TIMESTAMP(3) not null on update CURRENT_TIMESTAMP(3), WHO varchar(100) not null, constraint PLAYS_TRACK_FK foreign key (TRACK) references TRACKS (ID) on update cascade, constraint PLAYS_WHO_FK foreign key (WHO) references USERS (USER) on update cascade on delete cascade ); create table if not exists PLAYLISTS ( ID bigint auto_increment primary key, NAME text not null, USER varchar(100) not null, constraint PLAYLISTS_USER_FK foreign key (USER) references USERS (USER) on update cascade on delete cascade ); create table if not exists PLAYLIST_TRACKS ( PLAYLIST bigint not null, TRACK varchar(191) not null, `INDEX` int not null, primary key (PLAYLIST, `INDEX`), constraint PLAYLIST_TRACKS_PLAYLIST_FK foreign key (PLAYLIST) references PLAYLISTS (ID) on update cascade on delete cascade, constraint PLAYLIST_TRACKS_TRACK_FK foreign key (TRACK) references TRACKS (ID) on update cascade on delete cascade );
true
4671f1a2b9fea32e6cce5af172a675e3b55d090e
SQL
GordinV/buh70
/sql/palk/create_view_palk.cur_puudumine.sql
UTF-8
1,386
3.1875
3
[]
no_license
DROP VIEW IF EXISTS palk.cur_puudumine; CREATE OR REPLACE VIEW palk.cur_puudumine AS SELECT p.id, p.lepingid, p.kpv1, p.kpv2, p.paevad, p.summa, p.puudumiste_liik :: VARCHAR(20) AS pohjus, p.tyyp, amet.nimetus AS amet, t.rekvid, a.regkood AS isikukood, a.nimetus AS isik, tyyp.eesti :: VARCHAR(20) AS liik, CASE WHEN p.puudumiste_liik = 'PUHKUS' AND p.tyyp <= 3 THEN TRUE WHEN p.puudumiste_liik = 'PUHKUS' AND p.tyyp > 4 THEN TRUE WHEN p.puudumiste_liik = 'HAIGUS' THEN TRUE ELSE FALSE END AS kas_muutab_kalendripäevad FROM palk.puudumine p INNER JOIN palk.tooleping t ON p.lepingid = t.id INNER JOIN libs.library amet ON t.ametid = amet.id INNER JOIN libs.asutus a ON t.parentid = a.id INNER JOIN palk.com_puudumiste_tyyp tyyp ON tyyp.liik = p.puudumiste_liik AND p.tyyp = tyyp.id WHERE p.status <> 'deleted'; GRANT SELECT ON TABLE palk.cur_puudumine TO dbpeakasutaja; GRANT SELECT ON TABLE palk.cur_puudumine TO dbkasutaja; GRANT ALL ON TABLE palk.cur_puudumine TO dbadmin; GRANT SELECT ON TABLE palk.cur_puudumine TO dbvaatleja; GRANT ALL ON TABLE palk.cur_puudumine TO taabel; /* select * from palk.cur_puudumine */
true
a03b2d101ce676732a655134e742db201d98597b
SQL
OlafMd/MedCon1.0
/mm-libs/dbaccess/Level 3/CL3_DeveloperTasks/Atomic/Retrieval/SQL/cls_Get_RecommendedDeveloperTaskList_for_ActiveUser.sql
UTF-8
2,176
3.203125
3
[]
no_license
Select tms_pro_developertasks.TMS_PRO_DeveloperTaskID AS DeveloperTask_ID From tms_pro_developertask_recommendations Inner Join tms_pro_projectmembers On tms_pro_developertask_recommendations.RecommendedTo_ProjectMember_RefID = tms_pro_projectmembers.TMS_PRO_ProjectMemberID Inner Join tms_pro_feature_2_developertask On tms_pro_developertask_recommendations.DeveloperTask_RefID = tms_pro_feature_2_developertask.DeveloperTask_RefID Inner Join tms_pro_feature On tms_pro_feature_2_developertask.Feature_RefID = tms_pro_feature.TMS_PRO_FeatureID Inner Join tms_pro_businesstask_2_feature On tms_pro_feature.TMS_PRO_FeatureID = tms_pro_businesstask_2_feature.Feature_RefID Inner Join tms_pro_businesstasks On tms_pro_businesstask_2_feature.BusinessTask_RefID = tms_pro_businesstasks.TMS_PRO_BusinessTaskID Inner Join tms_pro_projects On tms_pro_businesstasks.Project_RefID = tms_pro_projects.TMS_PRO_ProjectID Inner Join tms_pro_developertasks On tms_pro_developertask_recommendations.DeveloperTask_RefID = tms_pro_developertasks.TMS_PRO_DeveloperTaskID Where tms_pro_projectmembers.USR_Account_RefID = @AccountID And tms_pro_developertask_recommendations.Tenant_RefID = @TenantID And tms_pro_developertask_recommendations.IsDeleted = 0 And tms_pro_projects.Status_RefID != @ProjectStatusExcluded And tms_pro_projects.IsArchived = 0 And tms_pro_projects.IsDeleted = 0 And tms_pro_businesstasks.Task_Status_RefID != @BusinessTaskStatusExcluded And tms_pro_businesstasks.IsArchived = 0 And tms_pro_businesstasks.IsDeleted = 0 And tms_pro_feature.Status_RefID != @FeatureStatusExcluded And tms_pro_feature.IsArchived = 0 And tms_pro_feature.IsDeleted = 0 And tms_pro_developertasks.IsDeleted = 0 And tms_pro_developertasks.IsArchived = 0 And (tms_pro_developertasks.IsBeingPrepared = 1 Or tms_pro_developertasks.IsBeingPrepared = @IsBeingPrepared_Only Or tms_pro_developertasks.IsBeingPrepared Is Null) And tms_pro_developertasks.Project_RefID = @ProjectID_List And tms_pro_developertasks.GrabbedByMember_RefID = Cast(0x00000000000000000000000000000000 As Binary)
true
b885a37fe3e89b8a23ba8c21b19c4d9dab9ed96e
SQL
chipbuster/skull-atlas
/scripts/SQL/genDB.sql
UTF-8
432
2.96875
3
[ "BSD-3-Clause" ]
permissive
/* This file is meant to be used to generate a standard schema for the * skull atlas project. * Let ${DB} be the file that sqlite3 uses to store the database. To use * this script, simply run sqlite3 ${DB} < genDB.sql. * Note that this will fail if the tables already exist within the db. */ create table metrics(patientid TEXT, metricname TEXT, metricval REAL); create table patient(patientid TEXT, gender TEXT, age INTEGER);
true
0fb55dc6fc8c66ac82bf9dabb02f62692be88aea
SQL
vigneshvkp/Asp-Internal-Work
/temp.sql
UTF-8
14,758
3.703125
4
[]
no_license
DROP TABLE IF EXISTS `assesment_group`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `assesment_group` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `group_name` varchar(50) CHARACTER SET latin1 NOT NULL, `description` varchar(255) CHARACTER SET latin1 NOT NULL, `assesment_type_id` int(10) unsigned NOT NULL, `created_by` varchar(10) DEFAULT NULL, `created_on` datetime DEFAULT NULL, `last_modified_by` varchar(10) DEFAULT NULL, `last_modified_on` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `FK_ass_group_ass_type` (`assesment_type_id`), CONSTRAINT `FK_ass_group_ass_type` FOREIGN KEY (`assesment_type_id`) REFERENCES `assesment_type` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8 COMMENT='Assesment Groups'; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `assesment_group_checklist`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `assesment_group_checklist` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `group_checklist` varchar(1000) NOT NULL, `assesment_group_id` int(10) unsigned NOT NULL, `created_by` varchar(10) DEFAULT NULL, `created_on` datetime DEFAULT NULL, `last_modified_by` varchar(10) DEFAULT NULL, `last_modified_on` datetime DEFAULT NULL, `heading` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`), KEY `FK_ass_grp_chklist_ass_group` (`assesment_group_id`) USING BTREE, CONSTRAINT `FK_ass_grp_chklist_ass_group` FOREIGN KEY (`assesment_group_id`) REFERENCES `assesment_group` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=151 DEFAULT CHARSET=utf8 COMMENT='CheckList Item for Assesment Groups'; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `assesment_line_item`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `assesment_line_item` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `line_item_text` varchar(50) CHARACTER SET latin1 NOT NULL, `line_item_description` varchar(350) DEFAULT NULL, `assesment_group_id` int(10) unsigned NOT NULL, `assesment_type_id` int(10) unsigned DEFAULT NULL, `created_by` varchar(10) NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) NOT NULL, `last_modified_on` datetime NOT NULL, PRIMARY KEY (`id`), KEY `FK_ass_line_item_ass_group` (`assesment_group_id`) USING BTREE, KEY `FK_ass_line_item_ass_type` (`assesment_type_id`) USING BTREE, CONSTRAINT `FK_ass_line_item_ass_group` FOREIGN KEY (`assesment_group_id`) REFERENCES `assesment_group` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_ass_line_item_ass_type` FOREIGN KEY (`assesment_type_id`) REFERENCES `assesment_type` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8 COMMENT='Assessment Line item'; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `assesment_type`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `assesment_type` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) CHARACTER SET latin1 NOT NULL, `description` varchar(255) CHARACTER SET latin1 DEFAULT NULL, `created_by` varchar(10) DEFAULT NULL, `created_on` datetime DEFAULT NULL, `last_modified_by` varchar(10) DEFAULT NULL, `last_modified_on` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='Various Asssment Types'; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `auditor`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auditor` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `ace_no` varchar(10) NOT NULL, `name` varchar(255) NOT NULL, `active` bit(1) NOT NULL DEFAULT b'1', `dept_id` varchar(10) NOT NULL, `dept_name` varchar(50) NOT NULL, `email` varchar(255) NOT NULL, `created_by` varchar(10) NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) NOT NULL, `last_modified_on` datetime NOT NULL, PRIMARY KEY (`id`), KEY `NewIndex1` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=117 DEFAULT CHARSET=utf8 COMMENT='Auditor Log'; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `customer`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `customer` ( `id` int(10) unsigned NOT NULL, `customer_name` varchar(100) NOT NULL, `active` bit(1) NOT NULL DEFAULT b'1', `created_by` varchar(10) NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) NOT NULL, `last_modified_on` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `department`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `department` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `pros_dept_id` varchar(10) NOT NULL, `name` varchar(100) NOT NULL, `dept_head_ace_no` varchar(10) NOT NULL, `created_by` varchar(10) NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) NOT NULL, `last_modified_on` datetime NOT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=98 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `project`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `project` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `pros_project_id` int(10) unsigned NOT NULL, `prj_name` varchar(100) CHARACTER SET latin1 NOT NULL, `active` tinyint(1) NOT NULL DEFAULT '1', `start_date` datetime NOT NULL, `end_date` datetime DEFAULT NULL, `created_by` varchar(10) NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) NOT NULL, `last_modified_on` datetime NOT NULL, `audit_freq` tinyint(2) unsigned NOT NULL DEFAULT '2', `customer_id` int(10) unsigned NOT NULL, `dept_id` int(10) unsigned NOT NULL, `owner_user_id` varchar(10) NOT NULL, PRIMARY KEY (`id`), KEY `FK_project_pros_project` (`pros_project_id`), KEY `FK_project_department` (`dept_id`), KEY `FK_project_customer` (`customer_id`), CONSTRAINT `FK_project_customer` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`), CONSTRAINT `FK_project_department` FOREIGN KEY (`dept_id`) REFERENCES `department` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=812 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `project_auditee_mapping`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `project_auditee_mapping` ( `id` int(11) NOT NULL AUTO_INCREMENT, `audit_id` int(11) DEFAULT NULL, `score_id` int(11) DEFAULT NULL, `auditee_name` varchar(100) DEFAULT NULL, `created_by` varchar(10) DEFAULT NULL, `created_on` datetime DEFAULT NULL, `lastmodified_by` varchar(10) DEFAULT NULL, `lastmodified_on` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3091 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `project_auditor_history`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `project_auditor_history` ( `id` int(11) NOT NULL AUTO_INCREMENT, `project_id` int(11) NOT NULL, `auditor_id` int(11) NOT NULL, `created_by` varchar(10) NOT NULL, `created_on` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=760 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `project_auditor_mapping`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `project_auditor_mapping` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `project_id` int(10) unsigned NOT NULL, `auditor_id` int(10) unsigned NOT NULL, `audit_date` datetime NOT NULL, `audit_complete` tinyint(1) NOT NULL DEFAULT '0', `created_by` varchar(10) NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) NOT NULL, `last_modified_on` datetime NOT NULL, PRIMARY KEY (`id`), KEY `FK_prj_adtr_map_auditors` (`auditor_id`), KEY `FK_prj_adtr_map_projects` (`project_id`), CONSTRAINT `FK_prj_adtr_map_auditors` FOREIGN KEY (`auditor_id`) REFERENCES `auditor` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_prj_adtr_map_projects` FOREIGN KEY (`project_id`) REFERENCES `project` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=739 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `thi_group_score`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `thi_group_score` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `thi_score_id` int(10) unsigned NOT NULL, `project_id` int(10) unsigned NOT NULL, `assessment_group_id` int(10) unsigned NOT NULL, `score` decimal(10,0) NOT NULL, `created_by` varchar(10) NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) NOT NULL, `last_modified_on` datetime NOT NULL, PRIMARY KEY (`id`), KEY `FK_thi_group_score_thi_score` (`thi_score_id`), KEY `FK_thi_group_score_project` (`project_id`), KEY `FK_thi_group_score_assesment_group` (`assessment_group_id`), CONSTRAINT `FK_thi_group_score_assesment_group` FOREIGN KEY (`assessment_group_id`) REFERENCES `assesment_group` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_thi_group_score_project` FOREIGN KEY (`project_id`) REFERENCES `project` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_thi_group_score_thi_score` FOREIGN KEY (`thi_score_id`) REFERENCES `thi_score` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=5189 DEFAULT CHARSET=utf8 COMMENT='First level child table of Thi Score'; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `thi_line_item_log`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `thi_line_item_log` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `thi_group_score_id` int(10) unsigned NOT NULL, `thi_score_id` int(10) unsigned NOT NULL, `assesment_line_item_id` int(10) unsigned NOT NULL, `comments` varchar(1000) CHARACTER SET latin1 DEFAULT NULL, `created_by` varchar(10) CHARACTER SET latin1 NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) CHARACTER SET latin1 NOT NULL, `last_modified_on` datetime NOT NULL, PRIMARY KEY (`id`), KEY `FK_thi_line_item_log_thi_group_score` (`thi_group_score_id`), KEY `FK_thi_line_item_log_thi_score` (`thi_score_id`), KEY `FK_thi_line_item_log_assesment_line_item` (`assesment_line_item_id`), CONSTRAINT `FK_thi_line_item_log_assesment_line_item` FOREIGN KEY (`assesment_line_item_id`) REFERENCES `assesment_line_item` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_thi_line_item_log_thi_group_score` FOREIGN KEY (`thi_group_score_id`) REFERENCES `thi_group_score` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_thi_line_item_log_thi_score` FOREIGN KEY (`thi_score_id`) REFERENCES `thi_score` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=13425 DEFAULT CHARSET=utf8 COMMENT='THI Score''s second level detail table'; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `thi_score`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `thi_score` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `project_id` int(10) unsigned NOT NULL, `auditor_id` int(10) unsigned NOT NULL, `audit_date` datetime NOT NULL, `audit_cycle_date` datetime NOT NULL, `overall_score` decimal(10,2) NOT NULL, `comments` varchar(1000) CHARACTER SET latin1 DEFAULT NULL, `recommendations` varchar(1000) CHARACTER SET latin1 DEFAULT NULL, `project_owner_id` varchar(10) CHARACTER SET latin1 NOT NULL, `assesment_type_id` int(10) unsigned NOT NULL, `created_by` varchar(10) CHARACTER SET latin1 NOT NULL, `created_on` datetime NOT NULL, `last_modified_by` varchar(10) CHARACTER SET latin1 NOT NULL, `last_modified_on` datetime NOT NULL, PRIMARY KEY (`id`), KEY `FK_thi_score_project` (`project_id`), KEY `FK_thi_score_auditor` (`auditor_id`), KEY `FK_thi_score` (`assesment_type_id`), CONSTRAINT `FK_thi_score` FOREIGN KEY (`assesment_type_id`) REFERENCES `assesment_type` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_thi_score_auditor` FOREIGN KEY (`auditor_id`) REFERENCES `auditor` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_thi_score_project` FOREIGN KEY (`project_id`) REFERENCES `project` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=741 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='Thi Scoring Matser Table'; /*!40101 SET character_set_client = @saved_cs_client */; DROP TABLE IF EXISTS `thi_line_item_score`; create table thi_line_item_score( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `thi_score_id` int(10) unsigned NOT NULL, `assesment_line_item_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `FK_thi_line_item_log_thi_score` (`thi_score_id`), KEY `FK_thi_line_item_score_assesment_line_item` (`assesment_line_item_id`), CONSTRAINT `FK_thi_line_item_log_thi_score` FOREIGN KEY (`thi_score_id`) REFERENCES `thi_score` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_thi_line_item_score_assesment_line_item` FOREIGN KEY (`assesment_line_item_id`) REFERENCES `assesment_line_item` (`id`) ON UPDATE CASCADE, ) CREATE TABLE `thi_line_item_score` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `thi_score_id` int(10) unsigned NOT NULL, `assesment_line_item_id` int(10) unsigned NOT NULL, `score` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `FK_thi_line_item_score_thi_score` (`thi_score_id`), KEY `FK_thi_line_item_score_assesment_line_item` (`assesment_line_item_id`), CONSTRAINT `FK_thi_line_item_score_thi_score` FOREIGN KEY (`thi_score_id`) REFERENCES `thi_score` (`id`) ON UPDATE CASCADE, CONSTRAINT `FK_thi_line_item_score_assesment_line_item` FOREIGN KEY (`assesment_line_item_id`) REFERENCES `assesment_line_item` (`id`) ON UPDATE CASCADE );
true
574caf93e6fca4590d5730d848bd3cccaf6b3318
SQL
milafiolita/mysql
/task1.sql
UTF-8
5,140
3.234375
3
[]
no_license
-- MySQL dump 10.13 Distrib 5.7.21, for osx10.13 (x86_64) -- -- Host: localhost Database: task1 -- ------------------------------------------------------ -- Server version 5.7.21 /*!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 */; /*!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 */; -- -- Temporary table structure for view `student_chart` -- DROP TABLE IF EXISTS `student_chart`; /*!50001 DROP VIEW IF EXISTS `student_chart`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; /*!50001 CREATE VIEW `student_chart` AS SELECT 1 AS `month`, 1 AS `frek`*/; SET character_set_client = @saved_cs_client; -- -- Table structure for table `students` -- DROP TABLE IF EXISTS `students`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `students` ( `student_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `admission_date` date DEFAULT NULL, `name` varchar(100) NOT NULL, `address` varchar(150) NOT NULL, `gender` enum('F','M') NOT NULL, `date_of_birth` date NOT NULL, `student_email` varchar(100) NOT NULL, PRIMARY KEY (`student_id`) ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `students` -- LOCK TABLES `students` WRITE; /*!40000 ALTER TABLE `students` DISABLE KEYS */; INSERT INTO `students` VALUES (1,'2017-01-10','Mila Fiolita','Semarang','F','1995-01-06','[email protected]'),(2,'2017-01-12','Septiana Adityarini','Semarang','F','1995-09-24','[email protected]'),(3,'2017-02-02','Vika Astriani','Semarang','F','1995-03-03','[email protected]'),(4,'2017-02-10','Reni Puji L','Solo','F','1996-05-06','[email protected]'),(5,'2017-02-21','Rully Indra','Yogyakarta','F','1996-02-02','[email protected]'),(6,'2017-03-08','Andre Bagus','Kediri','M','1995-03-02','[email protected]'),(7,'2017-03-16','Tomy Soeharto','Ungaran','M','1995-11-10','[email protected]'),(8,'2017-03-31','Hendry Ainur','Surabaya','M','1995-12-17','[email protected]'),(9,'2017-04-22','Qisti Rahmatillah','Indramayu','F','1995-05-17','[email protected]'),(10,'2017-04-30','Dyah Ayu','Wonogiri','F','1995-04-20','[email protected]'),(11,'2017-05-13','Ivanda','Magelang','M','1995-08-23','[email protected]'),(12,'2017-05-13','Tyok','Ungaran','M','1995-11-15','[email protected]'),(13,'2017-05-13','Fandi Rahman','Kendal','M','1995-01-17','[email protected]'),(14,NULL,'Hana Ayu','Jogja','F','1995-06-13','[email protected]'),(17,'2018-03-23','Indra','Magelang','M','2018-03-12','[email protected]'); /*!40000 ALTER TABLE `students` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `user` -- DROP TABLE IF EXISTS `user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(200) NOT NULL, `password` varchar(200) NOT NULL, `user_email` varchar(100) NOT NULL, `user_forgot` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `user` -- LOCK TABLES `user` WRITE; /*!40000 ALTER TABLE `user` DISABLE KEYS */; INSERT INTO `user` VALUES (1,'admin','89055a41e73fc65094b0106145e9eb78e6da4e30','[email protected]','2b2e8d35163a206e0ca5bdaa21bccb74fd8dc1f1'),(2,'rully','c4f9390950f0360df55661efde6480a73f74a25d','[email protected]',NULL); /*!40000 ALTER TABLE `user` ENABLE KEYS */; UNLOCK TABLES; -- -- Final view structure for view `student_chart` -- /*!50001 DROP VIEW IF EXISTS `student_chart`*/; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; /*!50001 SET character_set_client = utf8 */; /*!50001 SET character_set_results = utf8 */; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ /*!50001 VIEW `student_chart` AS select month(`students`.`admission_date`) AS `month`,count(0) AS `frek` from `students` group by `students`.`admission_date` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; /*!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 2018-03-29 15:47:39
true
6fd6e67d3043c84613f9f1fab5c0e4599305fa8a
SQL
Vizzuality/trase
/db/views/ind_values_meta_mv_v01.sql
UTF-8
3,385
4.34375
4
[ "MIT" ]
permissive
WITH flow_paths AS ( SELECT DISTINCT(UNNEST(path)) AS node_id, context_id FROM flows ), nodes AS ( SELECT nodes.id, nodes.node_type_id, fp.context_id FROM flow_paths fp JOIN nodes ON fp.node_id = nodes.id ), node_values AS ( SELECT ind_id, context_id, country_id, commodity_id, ARRAY_AGG(DISTINCT node_type_id ORDER BY node_type_id) AS node_types_ids, ARRAY_AGG(DISTINCT year ORDER BY year) AS years FROM node_inds JOIN nodes ON node_inds.node_id = nodes.id JOIN contexts ON nodes.context_id = contexts.id GROUP BY ind_id, GROUPING SETS ( (context_id), (country_id), (commodity_id) ) ), node_values_by_context AS ( SELECT ind_id, JSONB_OBJECT_AGG( context_id, JSONB_BUILD_OBJECT('years', years, 'node_types_ids', node_types_ids) ) AS node_values FROM node_values WHERE commodity_id IS NULL AND country_id IS NULL AND context_id IS NOT NULL GROUP BY ind_id ), node_values_by_country AS ( SELECT ind_id, JSONB_OBJECT_AGG( country_id, JSONB_BUILD_OBJECT('years', years, 'node_types_ids', node_types_ids) ) AS node_values FROM node_values WHERE commodity_id IS NULL AND country_id IS NOT NULL AND context_id IS NULL GROUP BY ind_id ), node_values_by_commodity AS ( SELECT ind_id, JSONB_OBJECT_AGG( commodity_id, JSONB_BUILD_OBJECT('years', years, 'node_types_ids', node_types_ids) ) AS node_values FROM node_values WHERE commodity_id IS NOT NULL AND country_id IS NULL AND context_id IS NULL GROUP BY ind_id ), flow_values AS ( SELECT ind_id, context_id, country_id, commodity_id, ARRAY_AGG(DISTINCT year ORDER BY year) AS years FROM flow_inds JOIN flows ON flow_inds.flow_id = flows.id JOIN contexts ON flows.context_id = contexts.id GROUP BY ind_id, GROUPING SETS ( (context_id), (country_id), (commodity_id) ) ), flow_values_by_context AS ( SELECT ind_id, JSONB_OBJECT_AGG( context_id, JSONB_BUILD_OBJECT('years', years) ) AS flow_values FROM flow_values WHERE commodity_id IS NULL AND country_id IS NULL AND context_id IS NOT NULL GROUP BY ind_id ), flow_values_by_country AS ( SELECT ind_id, JSONB_OBJECT_AGG( country_id, JSONB_BUILD_OBJECT('years', years) ) AS flow_values FROM flow_values WHERE commodity_id IS NULL AND country_id IS NOT NULL AND context_id IS NULL GROUP BY ind_id ), flow_values_by_commodity AS ( SELECT ind_id, JSONB_OBJECT_AGG( commodity_id, JSONB_BUILD_OBJECT('years', years) ) AS flow_values FROM flow_values WHERE commodity_id IS NOT NULL AND country_id IS NULL AND context_id IS NULL GROUP BY ind_id ) SELECT inds.id AS ind_id, JSONB_BUILD_OBJECT( 'context', nv1.node_values, 'country', nv2.node_values, 'commodity', nv3.node_values ) AS node_values, JSONB_BUILD_OBJECT( 'context', fv1.flow_values, 'country', fv2.flow_values, 'commodity', fv3.flow_values ) AS flow_values FROM inds LEFT JOIN node_values_by_context nv1 ON nv1.ind_id = inds.id LEFT JOIN node_values_by_country nv2 ON nv2.ind_id = inds.id LEFT JOIN node_values_by_commodity nv3 ON nv3.ind_id = inds.id LEFT JOIN flow_values_by_context fv1 ON fv1.ind_id = inds.id LEFT JOIN flow_values_by_country fv2 ON fv2.ind_id = inds.id LEFT JOIN flow_values_by_commodity fv3 ON fv3.ind_id = inds.id;
true
7c163c3cca655558688c8845943e9c16cd562dbd
SQL
bew61990/SE3910CommerceProject
/Final Prototype (Dec6)/Final Prototype (Dec6)/test2Prototype/create_db.sql
UTF-8
1,163
3.203125
3
[]
no_license
CREATE DATABASE SportsChatApp; CREATE TABLE users ( user_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(20) NOT NULL, pass VARCHAR(128) NOT NULL, email VARCHAR(60) NOT NULL, fav_player INTEGER UNSIGNED, fav_team INTEGER UNSIGNED, PRIMARY KEY (user_id) ); CREATE TABLE teams ( team_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, team_name VARCHAR(20) NOT NULL, PRIMARY KEY (team_id) ); CREATE TABLE players ( player_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, player_name VARCHAR(50) NOT NULL, team_id INTEGER UNSIGNED NOT NULL, PRIMARY KEY(player_id) ); CREATE TABLE user_chatroom ( user_id INTEGER UNSIGNED, chatroom_id INTEGER UNSIGNED ); CREATE TABLE chatrooms ( chatroom_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, chatroom_name VARCHAR(20) NOT NULL, PRIMARY KEY(chatroom_id) ); CREATE TABLE chatroom_messages ( chatroom_id INTEGER UNSIGNED, message_id INTEGER UNSIGNED ); CREATE TABLE messages ( message_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, user_id INTEGER NOT NULL, message_content VARCHAR(140) NOT NULL, date VARCHAR(25) NOT NULL, PRIMARY KEY(message_id) );
true
528bc5f4ccdb7a90a345c06f75fefb8379051953
SQL
mujurin/project-d3.js
/baciroui/baciro.sql
UTF-8
2,198
2.828125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.0.10deb1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 14, 2016 at 03:59 PM -- Server version: 5.5.49-0ubuntu0.14.04.1 -- PHP Version: 5.5.9-1ubuntu4.17 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: `baciro` -- -- -------------------------------------------------------- -- -- Table structure for table `role` -- CREATE TABLE IF NOT EXISTS `role` ( `role_id` int(11) NOT NULL AUTO_INCREMENT, `role_name` varchar(45) DEFAULT NULL, PRIMARY KEY (`role_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `role` -- INSERT INTO `role` (`role_id`, `role_name`) VALUES (1, 'Administrator'); -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE IF NOT EXISTS `user` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(45) DEFAULT NULL, `lastname` varchar(45) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `apikey` varchar(255) DEFAULT NULL, `create_date` datetime DEFAULT NULL, `update_date` datetime DEFAULT NULL, `role_id` int(11) DEFAULT NULL, PRIMARY KEY (`user_id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `user_email_unique` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `user` -- INSERT INTO `user` (`user_id`, `firstname`, `lastname`, `email`, `password`, `apikey`, `create_date`, `update_date`, `role_id`) VALUES (1, 'test', 'bro', '[email protected]', '$2a$10$dO0MJDEKRmcdwupDrbVFMO8Fa99.fhSmGlBeeM6les2zFCUSOd/wO', NULL, '2016-04-15 07:06:16', NULL, 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
dd3064c80dabf9c892816766c4fe058201fd2d45
SQL
Killor1/CampJPA
/summerCamp_schema.sql
UTF-8
1,599
3.515625
4
[]
no_license
CREATE TABLE cuidador ( dni char(9), nom varchar(30), telefon char(9), adreça varchar(100), email varchar(25), CONSTRAINT cuidador_pk PRIMARY KEY (dni), CONSTRAINT dni_valid_ck CHECK (dni ~*'[[:digit:]]{8}[[:alpha]]{1}') ); CREATE TABLE nen ( id_nen int, nom varchar(30), data_naixement date, cuidador char(9), CONSTRAINT nen_pk PRIMARY KEY (id_nen), CONSTRAINT nen_to_cuidador_fk FOREIGN KEY (cuidador) REFERENCES cuidador(dni) ); CREATE TABLE campament ( id_campament int, lloc varchar(30), data_inici date, data_fi date, CONSTRAINT campament_pk PRIMARY KEY (id_campament) ); CREATE TABLE campament_nens ( id_campament int, id_nen int, CONSTRAINT campament_nens_pk PRIMARY KEY (id_campament, id_nen), CONSTRAINT campament_nens2nen_fk FOREIGN KEY (id_nen) REFERENCES nen(id_nen), CONSTRAINT campament_nens2campament_fk FOREIGN KEY (id_campament) REFERENCES campament(id_campament) ); CREATE TABLE activitat ( id_activitat int, descripcio text, CONSTRAINT activitat_pk PRIMARY KEY (id_activitat) ); CREATE TABLE activitats_campament ( id_campament int, id_activitat int, CONSTRAINT activitats_campament_pk PRIMARY KEY (id_campament, id_activitat), CONSTRAINT activitats_campament2campament_fk FOREIGN KEY (id_campament) REFERENCES campament(id_campament), CONSTRAINT activitats_campament2activitat_fk FOREIGN KEY (id_activitat) REFERENCES activitat(id_activitat) );
true
7e637d98daff698468893c7f00e2069e8e53c12c
SQL
MurielPinho/FEUP-BDAD-Project
/3rd Delivery/Queries/int1.sql
UTF-8
312
3.90625
4
[]
no_license
.bail ON .mode columns .headers on .nullvalue NULL PRAGMA foreign_keys = ON; -- 1. Ranking of the channels by follower count. SELECT channel.name AS Channel, COUNT(follows.channelID) AS Followers FROM channel, follows WHERE channel.channelID = follows.channelID GROUP BY channel.name ORDER BY Followers DESC
true
a60a72c49f54e1684c18d2235cb1cc3a72698dd2
SQL
vikozlov89/iowa_liquor_sales_eda
/scripts/sql/query_basic_columns_stats.sql
UTF-8
5,220
2.6875
3
[]
no_license
SELECT 'Stats' as series_name , count(invoice_and_item_number) total_rows , count(distinct invoice_and_item_number) distinct_invoice_and_item_number_values , count(distinct date) days_tracked , min(date) earliest_day_tracked , max(date) latest_day_tracked , date_diff(max(date),min(date),DAY) time_period_tracked , count(date) * 1.0 / count(invoice_and_item_number) date_filled , count(distinct store_number) store_numbers_countd , count(store_number) *1.0 / count(invoice_and_item_number) store_numbers_filled , count(distinct store_name) store_names_countd , count(store_name) *1.0 / count(invoice_and_item_number) store_names_filled , count(distinct address) address_countd , count(address) *1.0 / count(invoice_and_item_number) address_filled , count(distinct city) city_countd , count(city) *1.0 / count(invoice_and_item_number) city_filled , count(distinct zip_code) zip_code_countd , count(zip_code) *1.0 / count(invoice_and_item_number) zip_code_filled , count(distinct store_location) store_location_countd , count(store_location) *1.0 / count(invoice_and_item_number) store_location_filled , count(distinct county_number) county_number_countd , count(county_number) *1.0 / count(invoice_and_item_number) county_number_filled , count(distinct county) county_countd , count(county) *1.0 / count(invoice_and_item_number) county_filled , count(distinct category) category_countd , count(category) *1.0 / count(invoice_and_item_number) category_filled , count(distinct category_name) category_name_countd , count(category_name) *1.0 / count(invoice_and_item_number) category_name_filled , count(distinct vendor_number) vendor_number_countd , count(vendor_number) *1.0 / count(invoice_and_item_number) vendor_number_filled , count(distinct vendor_name) vendor_name_countd , count(vendor_name) *1.0 / count(invoice_and_item_number) vendor_name_filled , count(distinct item_number) item_number_countd , count(item_number) *1.0 / count(invoice_and_item_number) item_number_filled , count(distinct item_description) item_description_countd , count(item_description) *1.0 / count(invoice_and_item_number) item_description_filled , count(distinct pack) pack_countd , count(pack) *1.0 / count(invoice_and_item_number) pack_filled , avg(pack*1.0) avg_pack_size , min(pack*1.0) min_pack_size , max(pack*1.0) max_pack_size , STDDEV_SAMP(pack*1.0) stddev_pack , count(distinct bottle_volume_ml) bottle_volume_ml_countd , count(bottle_volume_ml) *1.0 / count(invoice_and_item_number) bottle_volume_ml_filled , avg(bottle_volume_ml*1.0) avg_bottle_volume_ml , min(bottle_volume_ml*1.0) min_bottle_volume_ml , max(bottle_volume_ml*1.0) max_bottle_volume_ml , STDDEV_SAMP(bottle_volume_ml*1.0) stddev_bottle_volume_ml , count(state_bottle_cost) *1.0 / count(invoice_and_item_number) state_bottle_cost_filled , avg(state_bottle_cost*1.0) avg_state_bottle_cost , min(state_bottle_cost*1.0) min_state_bottle_cost , max(state_bottle_cost*1.0) max_state_bottle_cost , STDDEV_SAMP(state_bottle_cost*1.0) stddev_state_bottle_cost , count(state_bottle_retail) *1.0 / count(invoice_and_item_number) state_bottle_retail_filled , avg(state_bottle_retail*1.0) avg_state_bottle_retail , min(state_bottle_retail*1.0) min_state_bottle_retail , max(state_bottle_retail*1.0) max_state_bottle_retail , STDDEV_SAMP(state_bottle_retail*1.0) stddev_state_bottle_retail , count(distinct bottles_sold) bottles_sold_countd , count(bottles_sold) *1.0 / count(invoice_and_item_number) bottles_sold_filled , avg(bottles_sold*1.0) avg_bottles_sold , min(bottles_sold*1.0) min_bottles_sold , max(bottles_sold*1.0) max_bottles_sold , STDDEV_SAMP(bottles_sold*1.0) stddev_bottles_sold , count(distinct sale_dollars) sale_dollars_countd , count(sale_dollars) *1.0 / count(invoice_and_item_number) sale_dollars_filled , avg(sale_dollars*1.0) avg_sale_dollars , min(sale_dollars*1.0) min_sale_dollars , max(sale_dollars*1.0) max_sale_dollars , STDDEV_SAMP(sale_dollars*1.0) stddev_sale_dollars , count(distinct volume_sold_liters) volume_sold_liters_countd , count(volume_sold_liters) *1.0 / count(invoice_and_item_number) volume_sold_liters_filled , avg(volume_sold_liters*1.0) avg_volume_sold_liters , min(volume_sold_liters*1.0) min_volume_sold_liters , max(volume_sold_liters*1.0) max_volume_sold_liters , STDDEV_SAMP(volume_sold_liters*1.0) stddev_volume_sold_liters , count(distinct volume_sold_gallons) volume_sold_gallons_countd , count(volume_sold_gallons) *1.0 / count(invoice_and_item_number) volume_sold_gallons_filled , avg(volume_sold_gallons*1.0) avg_volume_sold_gallons , min(volume_sold_gallons*1.0) min_volume_sold_gallons , max(volume_sold_gallons*1.0) max_volume_sold_gallons , STDDEV_SAMP(volume_sold_gallons*1.0) stddev_volume_sold_gallons FROM `bigquery-public-data.iowa_liquor_sales.sales` GROUP BY 1
true
6d93e6a96b843abeb3a1f9b5e57aa814f6fe41ff
SQL
DilshanSamaraweera96/LMS
/db/sipsewana.sql
UTF-8
17,975
2.890625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: Jun 09, 2020 at 05:25 AM -- Server version: 5.7.26 -- PHP Version: 7.2.18 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 */; -- -- Database: `sipsewana` -- -- -------------------------------------------------------- -- -- Table structure for table `addbook` -- DROP TABLE IF EXISTS `addbook`; CREATE TABLE IF NOT EXISTS `addbook` ( `book_id` int(11) NOT NULL AUTO_INCREMENT, `title` text NOT NULL, `author` text NOT NULL, `category` text NOT NULL, `isbn` varchar(255) NOT NULL, `publisher` varchar(255) NOT NULL, `pages` int(11) NOT NULL, `quantity` int(11) NOT NULL, `language` text NOT NULL, `cover` text NOT NULL, `firstimage` text NOT NULL, `nextimage` text NOT NULL, PRIMARY KEY (`book_id`) ) ENGINE=MyISAM AUTO_INCREMENT=48 DEFAULT CHARSET=latin1; -- -- Dumping data for table `addbook` -- INSERT INTO `addbook` (`book_id`, `title`, `author`, `category`, `isbn`, `publisher`, `pages`, `quantity`, `language`, `cover`, `firstimage`, `nextimage`) VALUES (4, 'Artificial Intelligence', 'David L. Poole', 'IT', '9781107195394', 'Pearson Education India, 2005', 435, 8, 'English', 'itbook1.jpg', 'itbook12.jpg', 'itbook123.png'), (5, 'Learn Html & Css', 'Shay Howe', 'IT', '0133477576', 'New Riders, 2014 ', 304, 9, 'English', 'itbook2.jpg', 'itbook21.png', 'itbook22.png'), (6, 'Raspberry Pi CookBook', 'James Arthur', 'IT', '9781849696623', 'Packt Publishing Ltd, 2017', 402, 5, 'English', 'itbook3.jpg', 'itbook31.jpg', 'itbook32.jpg'), (7, 'Software Engineering', 'Caidin Sadowski', 'IT', '1484242211', 'Apress, 2016', 310, 8, 'English', 'itbook4.jpg', 'itbook41.jpg', 'itbook42.png'), (8, 'Design Patterns in Python', 'Chris Walker', 'IT', '9781788837484', 'Apress, 2017', 248, 1, 'English', 'itbook5.jpg', 'itbook51.jpg', 'itbook52.png'), (9, 'Python Design Patterns', 'Ron Wills', 'IT', '9781786460677', 'Packt Publishing Ltd, 2018', 286, 8, 'English', 'itbook6.jpg', 'itbook61.png', 'itbook62.png'), (10, 'Adaptive Code via C#', 'Gary Mclean', 'IT', '9780133979732', 'Microsoft Press, 2015', 448, 4, 'English', 'itbook7.jpg', 'itbook71.jpg', 'itbook72.png'), (11, 'Jumping Into C++', 'Alex Allain', 'IT', '0988927802', 'Cprogramming, 2014', 516, 9, 'English', 'itbook8.jpg', 'itbook81.png', 'itbook82.jpg'), (12, 'Math Geek', 'Raphael Rosen', 'Mathematics', '1440583811', 'Simon and Schuster, 2016', 256, 7, 'English', 'mathsbook1.jpg', 'mathsbook11.jpg', 'mathsbook12.jpg'), (13, 'Nature Science', 'Colin Rayman', 'Science', '0415070147', 'Psychology Press, 2012', 310, 5, 'English', 'science1.png', 'science11.jpg', 'science12.jpg'), (14, 'Animal Science', 'Alexandar Wilson', 'Science', '1428361278', 'Cengage Learning, 2005', 448, 6, 'English', 'science2.jpg', 'science21.jpg', 'science22.jpg'), (15, 'The Serpent Secret', 'Sayantani Dasgupta', 'Novel', '1338185721', 'Scholastic Incorporated, 2011', 368, 4, 'English', 'front2.jpg', 'novel11.jpg', 'novel12.jpg'), (16, 'Harry Poter', 'J.K. Rowling', 'Novel', '1408855658', 'Bloomsbury USA, 2014', 352, 8, 'English', 'front3.jpg', 'novel21.png', 'novel22.png'), (17, 'Its All In Your Head', 'Keith Blanchard', 'Art', '9780692918234', 'Wicked Cow Studios, 2017', 208, 6, 'English', 'art1.jpg', 'art11.jpg', 'art12.jpg'), (18, 'Fundamentals of Drawing', 'Barrington Barber', 'Art', '1848584105', 'Arcturus Publishing, 2005', 267, 8, 'English', 'art2.jpg', 'art21.jpg', 'art22.jpg'), (19, 'Einstein', 'Walter Isaacson', 'Biography', '0313330808', 'Greenwood Publishing Group, 2005', 161, 7, 'English', 'bio1.jpg', 'bio11.jpg', 'bio12.jpg'), (20, 'The Human Anatomy', 'Katelynn D. Harman', 'Health', '9781647645519', 'Knowledge Flow, 2014', 100, 7, 'English', 'health1.jpg', 'health11.jpg', 'health12.png'), (21, 'Golden Soil', 'Rupert McCall', 'Poetry', '1647645514', 'Rupert McCall, 2019', 156, 5, 'English', 'poetry1.jpg', 'poetry11.jpg', 'poetry12.jpg'), (22, 'Cook Book', 'Michelin Star', 'Cooking', '1625817887', 'Rose Publishing Company, 1877', 384, 7, 'English', 'cook1.png', 'cook11.jpg', 'cook12.png'), (23, 'Cinderella', 'Barbara Watson', 'Kids', '1625814569', 'Twin Sisters, 2017', 24, 7, 'English', 'kids1.jpg', 'kids11.png', 'kids12.png'), (24, 'Think Like A Boss', 'Benjamin Shah', 'Business', ' 1708780963', 'Independently Published, 2019', 157, 8, 'English', 'business1.jpg', 'business11.png', 'business12.png'), (25, 'Drugs In Sport', 'Neil Chester', 'Other', '1351838989', 'Taylor & Francis, 2018', 430, 8, 'English', 'other1.jpg', 'other11.png', 'other12.jpg'), (26, 'The Jewish Revolutionary', 'Michael Jones', 'Other', '0929891074', 'Fidelity Press, 2008', 1200, 5, 'English', 'front1.jpg', 'religious11.png', 'religious12.png'); -- -------------------------------------------------------- -- -- Table structure for table `adminlogin` -- DROP TABLE IF EXISTS `adminlogin`; CREATE TABLE IF NOT EXISTS `adminlogin` ( `username` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, PRIMARY KEY (`username`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `adminlogin` -- INSERT INTO `adminlogin` (`username`, `password`) VALUES ('admin', 'admin'); -- -------------------------------------------------------- -- -- Table structure for table `booknews` -- DROP TABLE IF EXISTS `booknews`; CREATE TABLE IF NOT EXISTS `booknews` ( `newsid` int(11) NOT NULL AUTO_INCREMENT, `topic` text NOT NULL, `msg` text NOT NULL, `cover` text NOT NULL, `newsdate` datetime DEFAULT NULL, PRIMARY KEY (`newsid`) ) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=latin1; -- -- Dumping data for table `booknews` -- INSERT INTO `booknews` (`newsid`, `topic`, `msg`, `cover`, `newsdate`) VALUES (1, 'RWA retires RITA Awards, debuts the \'Vivian\'', 'The Romance Writers of America will permanently retire its annual RITA Awards, which it has presented annually since 1982, and introduce a new award, the Vivian, named after RWA founder Vivian Stephens.\r\n\r\nThe move to retire the RITAs follows a controversy related to issues of diversity at the organization this winter that saw the resignation of its newly-instated president and its entire board of directors, as well as the cancellation of this year\'s planned RITA Awards ceremony. In January, the RWA announced that it planned to hold the RITAs again \"to celebrate 2019 and 2020 romances\" in 2021.', 'news1.jpg', '2020-05-20 12:47:05'), (2, 'The story behind ‘The Great Realisation,’ a post-pandemic bedtime tale', 'Before the pandemic, Tomos Roberts read his poems to crowds around London who, he confesses, were often more interested in what they were drinking than what he was saying. Now, hunkered down and out of work, he’s found a far more attentive audience that stretches around the world — and includes people who haven’t yet reached drinking age.\r\nRoberts’s poem, “The Great Realisation,” was released on YouTube on April 29 and has been viewed tens of millions of times. A simple rhyming tale read as a bedtime story, it takes on heavy themes — corporate greed, familial alienation, the pandemic — and somehow comes up with a happy ending. Set in an unspecified future, the poem looks back on pre-pandemic life and imagines a “great realisation” sparked by the scourge.', 'news2.jpg', '2020-05-22 12:47:05'), (3, 'Colson Whitehead: Black author makes Pulitzer Prize history', 'US author Colson Whitehead has become only the fourth writer ever to win the Pulitzer Prize for fiction twice.The African-American author was honored for The Nickel Boys, which chronicles the abuse of black boys at a juvenile reform school in Florida.\r\nWhitehead, a 50-year-old New Yorker, won the 2017 prize in the same category for his book Underground Railroad. With one for each week, we’ll get to rank up our Rocket Pass 6 with a twist. The four modes to be introduced are Dropshot Rumble, Beach Ball, Boomer Ball, and Rocket League’s latest addition (and casualty), Heatseeker.Before him, only Booth Tarkington, William Faulkner and John Updike had won the Pulitzer for fiction twice.', 'news3.jpg', '2020-05-25 12:47:05'), (4, 'Marvel Comics AUGUST 2020 Solicitations Cover Gallery', 'Marvel Comics has released its August 2020 solicitations, largely pieced together from titles that were not released in April and May along with titles that were rescheduled from June and July due to comic book distribution interruptions stemming from coronavirus.\r\nAlmost 30 years after the landmark story Future Imperfect, legendary INCREDIBLE HULK scribe Peter David returns to the far-future version of the Hulk known as Maestro — the master of what remains of the world. With astounding art from HULK veteran Dale Keown and up-and-comer Germán Peralta, Maestro will answer questions that have haunted Hulk fans for years — and inspire some new ones.', 'news4.jpg', '2020-05-28 12:47:05'), (11, 'New book added to the \'cooking\' book collection', 'As Sri Lanka is being rediscovered a travel destination, its varied cuisine is also under the spotlight. As well as absorbing influences from India, the Middle East, Far East Asia and myriad European invaders, the small island also has strong Singhalese and Tamil cooking traditions and this cookbook brings these styles together to showcase the best of the country’s culinary heritage. Dig into 100 recipes that celebrate the island’s wonderful ingredients, from okra and jackfruit to coconut and chillies, and explore its culture through original travel photography of the country, its kitchens and its people.', 'cook2.jpg', '2020-06-09 04:28:50'); -- -------------------------------------------------------- -- -- Table structure for table `chat` -- DROP TABLE IF EXISTS `chat`; CREATE TABLE IF NOT EXISTS `chat` ( `id` int(11) NOT NULL AUTO_INCREMENT, `msg_from` varchar(255) NOT NULL, `msg_to` varchar(255) NOT NULL, `msg` text NOT NULL, `date` datetime NOT NULL, `seen` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=48 DEFAULT CHARSET=latin1; -- -- Dumping data for table `chat` -- INSERT INTO `chat` (`id`, `msg_from`, `msg_to`, `msg`, `date`, `seen`) VALUES (47, 'hiruni nishadini', 'admin', 'not yet.', '2020-06-09 04:26:53', 'no'), (46, 'admin', 'hiruni nishadini', 'did you return the book?', '2020-06-09 02:57:13', 'no'), (45, 'admin', 'Bhagya Udathari', 'I Love You', '2020-06-08 05:33:33', 'no'), (41, 'admin', 'hashan hirapitya', 'did you eat dinner', '2020-06-07 23:16:01', 'no'), (42, 'admin', 'hiruni nishadini', 'how about today', '2020-06-08 00:09:03', 'no'), (43, 'admin', 'hiruni nishadini', 'good morning', '2020-06-08 04:15:45', 'no'), (44, 'hiruni nishadini', 'admin', 'good morning admin', '2020-06-08 05:11:00', 'no'), (40, 'admin', 'hashan hirapitya', 'whats up', '2020-06-07 19:50:28', 'no'), (39, 'admin', 'hashan hirapitya', 'hello hashan', '2020-06-07 19:50:19', 'no'), (38, 'admin', 'hiruni nishadini', 'hello hiruni', '2020-06-07 19:48:14', 'no'), (37, 'hiruni nishadini', 'admin', 'hello sir', '2020-06-07 19:13:42', 'no'), (35, 'admin', 'hiruni nishadini', 'Hello admin', '2020-06-07 19:04:58', 'no'), (36, 'hiruni nishadini', 'admin', 'hello admin', '2020-06-07 19:11:05', 'no'), (34, 'admin', 'hiruni nishadini', 'Hello admin', '2020-06-07 19:04:22', 'no'), (33, 'admin', 'hiruni nishadini', 'can i request book?', '2020-06-07 03:44:42', 'no'), (32, 'admin', 'hiruni nishadini', 'hello', '2020-06-07 03:27:32', 'no'); -- -------------------------------------------------------- -- -- Table structure for table `comments` -- DROP TABLE IF EXISTS `comments`; CREATE TABLE IF NOT EXISTS `comments` ( `comid` int(11) NOT NULL AUTO_INCREMENT, `member` varchar(100) NOT NULL, `comment` text NOT NULL, `comdate` datetime NOT NULL, PRIMARY KEY (`comid`) ) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=latin1; -- -- Dumping data for table `comments` -- INSERT INTO `comments` (`comid`, `member`, `comment`, `comdate`) VALUES (1, 'hashan hirapitya', 'This is the best online library website I ever visited.', '2020-06-02 16:01:57'), (2, 'Deshani Surangika', 'This is the only library which has this online website support in our area.This is a really good work.Keep it up.', '2020-06-03 13:29:25'), (3, 'pasidu kaushalya', 'This is a good website.', '2020-06-04 16:55:27'), (4, 'ADMIN', 'Thanks All of Your Support.', '2020-06-04 17:19:39'), (5, 'hiruni nishadini', 'Thanks for letting us to use this free service.', '2020-06-09 03:07:52'), (6, 'ADMIN', 'Appreciate your feedback.', '2020-06-09 03:55:35'); -- -------------------------------------------------------- -- -- Table structure for table `issuebook` -- DROP TABLE IF EXISTS `issuebook`; CREATE TABLE IF NOT EXISTS `issuebook` ( `issueid` int(11) NOT NULL AUTO_INCREMENT, `memberid` int(11) NOT NULL, `bookid` int(11) NOT NULL, `issuedate` date DEFAULT NULL, `collectdate` date DEFAULT NULL, `returndate` date DEFAULT NULL, `completedate` date DEFAULT NULL, `fine` float DEFAULT NULL, `payday` date DEFAULT NULL, PRIMARY KEY (`issueid`) ) ENGINE=MyISAM AUTO_INCREMENT=41 DEFAULT CHARSET=latin1; -- -- Dumping data for table `issuebook` -- INSERT INTO `issuebook` (`issueid`, `memberid`, `bookid`, `issuedate`, `collectdate`, `returndate`, `completedate`, `fine`, `payday`) VALUES (34, 10, 6, '2020-05-06', '2020-05-09', '2020-05-23', NULL, 85, NULL); -- -------------------------------------------------------- -- -- Table structure for table `notification` -- DROP TABLE IF EXISTS `notification`; CREATE TABLE IF NOT EXISTS `notification` ( `notid` int(11) NOT NULL AUTO_INCREMENT, `memberid` int(11) DEFAULT NULL, `bookid` int(11) DEFAULT NULL, `msg` text NOT NULL, `msgid` int(11) DEFAULT NULL, `date` datetime DEFAULT NULL, PRIMARY KEY (`notid`) ) ENGINE=MyISAM AUTO_INCREMENT=423 DEFAULT CHARSET=latin1; -- -- Dumping data for table `notification` -- INSERT INTO `notification` (`notid`, `memberid`, `bookid`, `msg`, `msgid`, `date`) VALUES (1, NULL, NULL, 'You collected the issued book.', 1, NULL), (2, NULL, NULL, 'You returned the issued book.', 2, NULL), (3, NULL, NULL, 'You paid the penalty for late return book.', 3, NULL), (12, NULL, NULL, 'Reservation removed because collect date expired.', 5, NULL), (10, NULL, NULL, 'Book is issued for your pending book request.', 4, NULL), (14, NULL, NULL, 'You have ONLY 3days left to return the book.', 6, NULL), (21, NULL, NULL, 'You didnt return the book within given time.Penalty will be charged now.', 7, NULL), (22, NULL, NULL, 'Today is the Last day to return your issued book.', 8, NULL), (23, NULL, NULL, 'You have only one day to collect your issued book.', 9, NULL), (419, 7, NULL, 'You returned the issued book.', NULL, '2020-07-07 05:02:53'), (418, 7, NULL, 'You collected the issued book.', NULL, '2020-07-07 05:02:42'), (417, 7, 47, 'You have only one day to collect your issued book.', NULL, '2020-07-07 05:02:34'), (420, 7, NULL, 'You returned the issued book.', NULL, '2020-07-07 05:07:08'), (421, 7, NULL, 'You paid the penalty for late return book.', NULL, '2020-07-07 05:07:13'), (414, 7, NULL, 'Book is issued for your pending book request.', NULL, '2020-07-05 04:57:14'), (422, 15, NULL, 'You paid the penalty for late return book.', NULL, '2020-07-07 05:13:09'), (409, 8, NULL, 'Reservation removed because collect date expired.', NULL, '2020-06-13 04:50:50'), (404, 10, NULL, 'You paid the penalty for late return book.', NULL, '2020-06-09 03:54:07'), (403, 10, NULL, 'You returned the issued book.', NULL, '2020-06-09 03:51:15'), (407, 8, 47, 'Today is the last day to collect your book.', NULL, '2020-06-12 04:50:25'), (396, NULL, NULL, 'Today is the last day to collect your book.', 10, NULL), (397, 1111111111, 1111111111, '111111111111111111111111111111111111111111111111111111111111111111111111111', 1111111111, NULL), (405, 8, NULL, 'Book is issued for your pending book request.', NULL, '2020-06-09 04:45:25'), (406, 8, 47, 'You have only one more to collect your issued book.', NULL, '2020-06-11 04:47:48'); -- -------------------------------------------------------- -- -- Table structure for table `user_register` -- DROP TABLE IF EXISTS `user_register`; CREATE TABLE IF NOT EXISTS `user_register` ( `mem-id` int(11) NOT NULL AUTO_INCREMENT, `fullname` varchar(255) NOT NULL, `address` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `phonenumber` int(11) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`mem-id`) ) ENGINE=MyISAM AUTO_INCREMENT=23 DEFAULT CHARSET=latin1; -- -- Dumping data for table `user_register` -- INSERT INTO `user_register` (`mem-id`, `fullname`, `address`, `email`, `phonenumber`, `password`) VALUES (7, 'Deshani Surangika', 'Horana,Kalutara', '[email protected]', 773455678, 'deshani'), (6, 'hiruni nishadini', 'waththala, gampaha', '[email protected]', 712342134, 'hiruni'), (8, 'hashan hirapitya', 'angoda, colombo', '[email protected]', 765673456, 'hashan'), (9, 'uditha madusanka', 'kahawaththa,mathale', '[email protected]', 713457856, 'uditha'), (10, 'pasidu kaushalya', 'beruwala,aluthgama', '[email protected]', 716784567, 'pasidu'), (12, 'anjana sampath', 'benthota,aluthgama', '[email protected]', 786784567, 'anjana'), (13, 'sithara samudiri', 'kiridiwela,mathara', '[email protected]', 714565634, 'sithara'), (14, 'lakshitha pramudith', 'dompe,gampaha', '[email protected]', 715673412, 'lakshitha'), (15, 'hoshan dinuk', 'jaela,gampaha', '[email protected]', 775677890, 'hoshan'), (16, 'yasura malshan', 'mathugama,kalutara', '[email protected]', 716784532, 'yasura'), (17, 'saman kumara', 'koswaththa,rathnapura', '[email protected]', 787896754, 'saman'), (18, 'isuru dilshan', 'mathugama,kalutara', '[email protected]', 711772177, 'isuru'), (19, 'hansika priyashani', 'meerigama,gampaha', '[email protected]', 785674356, 'hansika'), (20, 'nuwan perera', 'kakirawa,anuradhapura', '[email protected]', 785673456, 'nuwan'), (21, 'manuka pramod', 'thelwaththa,colombo', '[email protected]', 714567890, 'manuka'), (22, 'Bhagya Udathari', 'ovitigala,mathugama', '[email protected]', 714861060, 'bhagya'); 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
ad18b530717dd6344014793b310c50a9fdfe8f61
SQL
bgoldfarb/libraryDatabase
/mySQL_Queries/queries12.sql
UTF-8
1,480
4.125
4
[]
no_license
use l; SELECT SSN, Nme FROM EMPLOYEE WHERE SSN IN (SELECT ESSN FROM EMPDEP) UNION SELECT SSN, Nme FROM EMPLOYEE WHERE SSN IN (SELECT ManagerSSN FROM EMPLOYEE); SELECT SSN, Nme FROM EMPLOYEE WHERE SSN IN (SELECT ESSN FROM EMPDEP) AND SSN IN( SELECT SSN FROM EMPLOYEE WHERE SSN IN (SELECT ManagerSSN FROM EMPLOYEE)); SELECT SSN, Nme FROM EMPLOYEE WHERE Salary > 7000 AND SSN NOT IN( SELECT SSN FROM EMPLOYEE WHERE SSN IN (SELECT ManagerSSN FROM EMPLOYEE)); SELECT p.PubID, p.Nme FROM PUBLISHER as p WHERE NOT EXISTS (SELECT * FROM GAME as g WHERE g.PubID != p.PubID); SELECT b.ID, b.Nme, COUNT(m.MemberID) as mem_count FROM LIBRARY AS b, MEMBER AS m WHERE b.ID = m.LibraryID GROUP BY b.ID, b.Nme; SELECT b.BranchID, b.Nme as BranchName, e.SSN as EmpSSN, e.Nme as EmpName, e.Dflag as InDepartment, e.Sflag as InSection, d.DeptNo as DeptOrSectNum, d.DeptNme as DeptOrSectName FROM BRANCH as b, EMPLOYEE as e, DEPARTMENT as d WHERE b.BranchID = e.BranchID AND e.DeptNo = d.DeptNo AND e.BranchID = d.BranchID UNION SELECT bb.BranchID, bb.Nme as BranchName, ee.SSN as EmpSSN, ee.Nme as EmpName, ee.Dflag as InDepartment, ee.Sflag as InSection, ss.SectionID as DeptOrSectNum, ss.Nme as DeptOrSectName FROM BRANCH as bb, EMPLOYEE as ee, SECTION as ss WHERE bb.BranchID = ee.BranchID AND ee.SectionID = ss.SectionID AND ee.BranchID = ss.BranchID; SELECT CopyID, MemberID as LastHolderID, Nme as LastHolderName FROM MEMBER as m RIGHT OUTER JOIN CURSTATUS c ON m.MemberID=c.LastMID;
true
58a76c61033922bec0babbcd2dd97179a599382b
SQL
cosmic-cowboy/sql_head_training_cource
/10_set_operation_03/10_list08.sql
UTF-8
311
3.109375
3
[]
no_license
SELECT CASE WHEN age < 20 THEN '子供' WHEN age >= 20 AND age < 69 THEN '成人' WHEN age >= 70 THEN '老人' ELSE NULL END AS age_case, COUNT(*) FROM Persons GROUP BY CASE WHEN age < 20 THEN '子供' WHEN age >= 20 AND age < 69 THEN '成人' WHEN age >= 70 THEN '老人' ELSE NULL END
true
bb631257ae03e961ba2fa653584f4d8b44828438
SQL
LizeDong22/BlakeDong
/dopl.sql
UTF-8
2,092
3.03125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.7.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: Dec 13, 2019 at 12:59 PM -- Server version: 5.6.34-log -- PHP Version: 7.1.5 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 */; -- -- Database: `ruralhealth` -- -- -------------------------------------------------------- -- -- Table structure for table `dopl` -- CREATE TABLE `dopl` ( `LICENSE_NO` varchar(15) NOT NULL, `PROFESSION_NAME` varchar(50) DEFAULT NULL, `LICENSE_NAME` varchar(50) DEFAULT NULL, `DATE_OF_BIRTH` varchar(20) DEFAULT NULL, `ISSUE_DATE` varchar(20) DEFAULT NULL, `EXPIRATION_DATE` varchar(20) DEFAULT NULL, `LIC_STATUS` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `dopl` -- INSERT INTO `dopl` (`LICENSE_NO`, `PROFESSION_NAME`, `LICENSE_NAME`, `DATE_OF_BIRTH`, `ISSUE_DATE`, `EXPIRATION_DATE`, `LIC_STATUS`) VALUES ('5326968-6009', 'Clinical Mental Health', 'Assoc Clinical Mental Health Counselor', '1/27/1978', '2/27/2004', '2/27/2007', 'Expired'), ('7183390-6009', 'Clinical Mental Health', 'Assoc Clinical Mental Health Counselor', '8/2/1964', '11/24/2008', '11/24/2013', 'Superceded'), ('7199239-6009', 'Clinical Mental Health', 'Assoc Clinical Mental Health Counselor', '5/15/1970', '11/26/2008', '2/26/2013', 'Expired'), ('7280871-6009', 'Clinical Mental Health', 'Assoc Clinical Mental Health Counselor', '9/10/1969', '26/2/2009', '11/2/2012', 'Superceded'); -- -- Indexes for dumped tables -- -- -- Indexes for table `dopl` -- ALTER TABLE `dopl` ADD PRIMARY KEY (`LICENSE_NO`); 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
e3d117115a41607329b067862c2fe4b9eb52184b
SQL
cbush2014/MySQL-Employee-Tracker
/schema.sql
UTF-8
2,830
4.53125
5
[]
no_license
DROP DATABASE IF EXISTS ee_tracker; CREATE DATABASE ee_tracker; USE ee_tracker; CREATE TABLE departments ( department_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) ); CREATE TABLE roles ( role_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, title VARCHAR(30), salary DEC(10,2) DEFAULT 0, department_id INTEGER NOT NULL, CONSTRAINT departments_department_id_fk FOREIGN KEY (department_id) REFERENCES departments (department_id) ); CREATE TABLE employees ( ee_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(30), last_name VARCHAR(30), role_id INTEGER NOT NULL, CONSTRAINT roles_role_id_fk FOREIGN KEY (role_id) REFERENCES roles (role_id), manager_id INTEGER ); -- CRUD -- Intial table set up, load departments and roles -- first set up departments since roles table needs info from departments INSERT INTO departments (name) VALUES ('Sales'), ('Engineering'), ('Finance'), ('Legal'); -- 2nd set up roles, including foreign key from departments INSERT INTO roles ( title, salary, department_id) VALUES ('Sales Lead', 100000, 1), ('Sales Person', 80000, 1) ('Lead Engineer', 150000, 2) ('Software Engineer', 120000, 2) ('Accountant', 125000, 3) ('Legal Team Lead', 250000, 4) ('Lawyer', 190000, 4); INSERT INTO employees ( first_name, last_name, role_id, manager_id) VALUES ('Ashley', 'Rodriguez', 3, NULL), ('Malia','Brown', 5, NULL), ('Sarah', 'Lourd', 6, NULL) INSERT INTO employees ( first_name, last_name, role_id, manager_id) VALUES ('John', 'Doe', 1, 1) INSERT INTO employees ( first_name, last_name, role_id, manager_id) VALUES ('Mike', 'Chan', 2, 4), ('Kevin', 'Tupik', 4, 1), ('Tom', 'Allen', 7, 3) -- main select statement for view all employees SELECT e.ee_id, e.first_name, e.last_name, r.title, d.name, r.salary, CONCAT(mgr.first_name, " ", mgr.last_name) AS manager FROM employees AS e LEFT JOIN roles as r ON e.role_id = r.role_id LEFT JOIN employees as mgr ON e.manager_id = mgr.ee_id LEFT JOIN departments as d ON d.department_id = r.department_id SELECT e.ee_id, e.first_name, e.last_name, r.title, d.name, r.salary, mgr.first_name, mgr.last_name FROM employees AS e LEFT JOIN roles as r ON e.role_id = r.role_id LEFT JOIN employees as mgr ON e.manager_id = mgr.ee_id LEFT JOIN departments as d ON d.department_id = r.department_id ORDER BY d.name ASC -- List of Managers SELECT mgr.first_name, mgr.last_name, mgr.ee_id FROM employees AS e LEFT JOIN roles as r ON e.role_id = r.role_id INNER JOIN employees as mgr ON e.manager_id = mgr.ee_id LEFT JOIN departments as d ON d.department_id = r.department_id ORDER BY mgr.last_name ASC
true
03e1b3293094a638345a5d96209b8127fe3d3bce
SQL
geniot/adserverbeans
/db/procs/get_random_banner_by_traffic_share.sql
UTF-8
1,204
3.5625
4
[]
no_license
DELIMITER ;; DROP FUNCTION if exists get_random_banner_by_traffic_share; CREATE FUNCTION get_random_banner_by_traffic_share(valid_banners TEXT, total_traffic_share INTEGER) RETURNS INTEGER NOT DETERMINISTIC BEGIN DECLARE pos INTEGER DEFAULT 1; DECLARE rnd INTEGER DEFAULT 0; DECLARE current_traffic_share INTEGER DEFAULT 0; DECLARE banner_id INTEGER; DECLARE banner_traffic_share INTEGER; SET rnd = RAND()*(total_traffic_share-1)+1; WHILE pos < LENGTH(valid_banners) DO SET pos = POSITION(';' IN valid_banners); SET banner_id = CONVERT(SUBSTR(valid_banners,1,pos-1),SIGNED); SET valid_banners=SUBSTRING(valid_banners FROM pos+1); SET pos = POSITION(';' IN valid_banners); SET banner_traffic_share = CONVERT(SUBSTR(valid_banners,1,pos-1),SIGNED); SET valid_banners=SUBSTRING(valid_banners FROM pos+1); if(current_traffic_share < rnd and rnd <= (banner_traffic_share+current_traffic_share)) THEN RETURN banner_id; END IF; SET current_traffic_share=current_traffic_share+banner_traffic_share; END WHILE; END; ;; delimiter ;
true
ebc4c03c185d0c22b008423e417c24cf07e3b7b1
SQL
ivanborodkin1997/StartJava
/src/com/startjava/lesson_5/queries.sql
UTF-8
1,232
3.390625
3
[]
no_license
--queries SELECT * FROM Jeagers; --вывод всей таблицы SELECT * FROM Jeagers WHERE status = 'Active'; --отображение только не уничтоженных роботов SELECT * FROM Jeagers WHERE mark IN ('1','6'); --отображение роботов нескольких серий (Mark-1,6) SELECT * FROM Jeagers ORDER BY mark DESC; --отсортированная таблицы по убыванию по столбцу mark SELECT * FROM Jeagers WHERE launch = (SELECT MIN(launch) FROM Jeagers); --самый старый робот SELECT * FROM Jeagers WHERE kaijukill = (SELECT MAX(kaijukill) FROM Jeagers); --убил больше всех kaiju SELECT * FROM Jeagers WHERE kaijukill = (SELECT MIN(kaijukill) FROM Jeagers); --убил меньше всех kaiju SELECT AVG(weight) FROM Jeagers; --средний вес роботов UPDATE Jeagers SET kaijukill = kaijukill + 1 WHERE status = 'Active'; --увеличил на единицу количество уничтоженных kaiju у роботов, которые до сих пор не разрушены DELETE FROM Jeagers WHERE status = 'Distroyed'; --удалил уничтоженных роботов
true
61425cbb92aaf7c0c94e3417bf06b653be95f680
SQL
kristijnswinnen/Natuurpunt-wwf-lpi
/Natuurpunt-wwf-lpi dragonfly.sql
UTF-8
3,731
4.09375
4
[]
no_license
-- select all dragonflies with more than 30 recordings, create a temp table a drop table if exists a; create temp table a as (select v.id, naam_nl, naam_lat, count(distinct(w.id)) aantal from vogel v inner join waarneming w on (w.id_vogel=v.id) where v.ind_diergroep in (5) --dragonflies and id_species_type not in ('H','M') --no multispecies and date_part('year',w.datum) > 1999 --2000-2018 and date_part('year',w.datum) <2019 and w.id_activiteit not in (3103,3113) --no catch by cat or tracks and w.id_kleed not in (41,131,1104,1116) --No larvae, exuvia, egg or pro-larvae and w.ind_moderated not in ('N') --no observations which are considered to be incorrect by validators and w.aantal <> 0 --number of individuals needs to be different from zero and w.zeker = 'J' --only observervations of which the observer is sure are included and exact_meters <999 --geographical precision is higher than 999m group by v.id, naam_nl, naam_lat order by count(distinct(w.id)) desc limit 67); select distinct(a.id), naam_nl, naam_lat from a order by id asc -- calculate the percentage of observations to determine the flight period drop table if exists b; create temp table b as ( select a.id, date_part('month',w.datum) maand, date_part('day',w.datum) dag,a.aantal aantal_totaal, count(distinct(w.id)) aantal_vandaag, count(distinct(w.id))::decimal / a.aantal percentage, row_number() OVER (PARTITION BY a.id ORDER BY a.id) AS rnum from a inner join waarneming w on (w.id_vogel=a.id) where date_part('year',w.datum) > 1999 -- for parameter explanation, see above and date_part('year',w.datum) <2019 and w.id_activiteit not in (3103,3113) and w.id_kleed not in (41,131,1104,1116) and w.ind_moderated not in ('N') and w.aantal <> 0 and w.zeker = 'J' and exact_meters <999 group by a.id,date_part('month',w.datum), date_part('day',w.datum), a.aantal); drop table if exists c; create temp table c as ( select *, SUM(percentage) OVER (ORDER BY id, maand, dag) AS balance from b); drop table if exists d; create temp table d as ( select id,maand, dag,aantal_totaal,aantal_vandaag, balance , floor(balance), balance-floor(balance) percentage_van_de_vliegperiode from c); -- select only the 90% flightperiod select * from d where percentage_van_de_vliegperiode >= 0.05 and percentage_van_de_vliegperiode <= 0.95 -- Er is een tabel met de vliegperiode van de libellen gemaakt -- select data drop table if exists excl_vliegp; create temp table excl_vliegp as ( select w.id_vogel, date_part('year',w.datum) jaar, date_part('month',w.datum) maand, date_part('day',w.datum) dag, eea_1km gridcel, w.aantal from waarneming w inner join wnmn_gis as gis on (w.id = gis.w_id) where w.id_vogel in (587,594,631,616,640,641,613,589,578,590,629,627,585,610,1524,579,621,598,633,583,580,599,634,632,611,600,628,584,615,588,596,595,642,608,604,637,644,581,582,617,597,619,639,646,624,645,612,635,630,606,623,592,603,638,591,609,593,620,618,643,602,625,622,626,614,636,79647) --alle libellen met meer dan 30 wnmn and date_part('year',w.datum) > 1999 and date_part('year',w.datum) < 2019 and w.id_activiteit not in (3103,3113) --geen vangst door kat, sporen, and w.id_kleed not in (41,131,1104,1116) --larve/nimf, larvenhuidje, ei, prolarve and w.ind_moderated not in ('N') and w.aantal <> 0 and w.zeker = 'J' and exact_meters <999 order by w.id_vogel asc,date_part('month',w.datum) asc,date_part('day',w.datum) asc) -- nauwkeurigheid moet kleiner zijn dan een km. En staat als 999 gedefinieerd in de website. -- starting from these excl_vliegp the observations within the flightperiod were selected for analysis
true
d096f74970c95b6d5a5345ae7c5d2c08db1e2e87
SQL
MohamedHar0un/BookManagement
/todoapp.sql
UTF-8
3,285
3.40625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.1.14 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: May 31, 2015 at 08:18 PM -- Server version: 5.6.17 -- PHP Version: 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 */; -- -- Database: `todoapp` -- -- -------------------------------------------------------- -- -- Table structure for table `books` -- CREATE TABLE IF NOT EXISTS `books` ( `book_id` int(11) NOT NULL AUTO_INCREMENT, `book_name` varchar(255) NOT NULL, `book_cover` varchar(255) DEFAULT NULL, `book_url` varchar(255) NOT NULL, `user_id` int(11) NOT NULL, `start_date` date NOT NULL, `end_date` date NOT NULL, `page_number` int(11) NOT NULL DEFAULT '1', `pages_numbers` int(11) NOT NULL, `time_period` int(11) NOT NULL, `pages_per_day` int(11) NOT NULL, `Current_date` date NOT NULL, PRIMARY KEY (`book_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; -- -------------------------------------------------------- -- -- Table structure for table `comments` -- CREATE TABLE IF NOT EXISTS `comments` ( `comment_id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `question_id` int(11) NOT NULL, `comment_poster` varchar(100) NOT NULL, `comment_body` varchar(300) NOT NULL, `comment_upvotes` int(11) NOT NULL, `comment_downvotes` int(11) NOT NULL, `current_date` date NOT NULL, PRIMARY KEY (`comment_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(200) NOT NULL, `lastname` varchar(200) NOT NULL, `username` varchar(200) NOT NULL, `password` varchar(200) NOT NULL, `email` varchar(200) NOT NULL, `status` int(1) NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; -- -------------------------------------------------------- -- -- Table structure for table `user_voting` -- CREATE TABLE IF NOT EXISTS `user_voting` ( `user_id` int(11) NOT NULL, `question_id` int(11) NOT NULL, `vote_up` int(11) NOT NULL DEFAULT '0', `vote_down` int(11) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `voting_count` -- CREATE TABLE IF NOT EXISTS `voting_count` ( `question_id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `user_name` varchar(100) NOT NULL, `question_title` varchar(100) NOT NULL, `question_body` varchar(400) NOT NULL, `vote_up` int(11) NOT NULL, `vote_down` int(11) NOT NULL, `current_date` date NOT NULL, PRIMARY KEY (`question_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ; /*!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
27aa2a0fda74d9c5ebf0b91f13ea9e68dfe85f07
SQL
toun0u/CaamhroApi
/app/install/forms/structure.sql
UTF-8
4,572
2.890625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 2.11.2 -- http://www.phpmyadmin.net -- -- Host: mysql1.netlorconcept.com -- Generation Time: Apr 17, 2008 at 06:41 AM -- Server version: 4.0.27 -- PHP Version: 5.2.0-8+etch10 -- -------------------------------------------------------- -- -- Table structure for table `dims_mod_forms` -- DROP TABLE IF EXISTS `dims_mod_forms`; CREATE TABLE IF NOT EXISTS `dims_mod_forms` ( `id` int(10) unsigned NOT NULL auto_increment, `label` varchar(255) default NULL, `tablename` varchar(255) NOT NULL default '', `description` longtext, `pubdate_start` varchar(14) default NULL, `pubdate_end` varchar(14) default NULL, `email` varchar(255) default NULL, `option_onlyone` tinyint(1) unsigned default '0', `option_onlyoneday` tinyint(1) unsigned default '0', `width` varchar(5) NOT NULL default '*', `nbline` int(10) unsigned default '25', `model` varchar(32) default NULL, `typeform` varchar(16) default 'app', `option_modify` varchar(16) NOT NULL default 'nobody', `option_view` varchar(16) NOT NULL default 'global', `option_displayuser` tinyint(1) unsigned default '0', `option_displaygroup` tinyint(1) unsigned default '0', `option_displaydate` tinyint(1) unsigned default '0', `option_displayip` tinyint(1) unsigned default '0', `viewed` int(10) unsigned default '0', `autobackup` int(10) unsigned default '0', `cms_response` longtext, `cms_link` tinyint(1) unsigned default '0', `id_user` int(10) unsigned default '0', `id_workspace` int(10) unsigned default '0', `id_module` int(10) unsigned default '0', `timestp_modify` bigint(14) NOT NULL default '0', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), KEY `id_2` (`id`) ) TYPE=MyISAM AUTO_INCREMENT=16 ; -- -------------------------------------------------------- -- -- Table structure for table `dims_mod_forms_field` -- DROP TABLE IF EXISTS `dims_mod_forms_field`; CREATE TABLE IF NOT EXISTS `dims_mod_forms_field` ( `id` int(10) unsigned NOT NULL auto_increment, `id_forms` int(10) unsigned default '0', `name` varchar(255) default NULL, `fieldname` varchar(255) NOT NULL default '', `separator` tinyint(1) unsigned default '0', `separator_level` int(10) unsigned default '0', `separator_fontsize` int(10) unsigned default '0', `type` varchar(16) default NULL, `format` varchar(16) default NULL, `values` longtext, `description` longtext, `position` int(10) unsigned default '0', `maxlength` int(10) unsigned default '0', `cols` int(10) unsigned default '0', `option_needed` tinyint(1) unsigned default '0', `option_arrayview` tinyint(1) unsigned default '1', `option_exportview` tinyint(1) unsigned default '1', `option_cmsgroupby` tinyint(1) unsigned default '0', `option_cmsorderby` tinyint(1) unsigned default '0', `option_cmsdisplaylabel` tinyint(1) unsigned default '0', `option_cmsshowfilter` tinyint(1) unsigned default '0', `defaultvalue` varchar(255) default NULL, `interline` int(10) unsigned NOT NULL default '0', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), KEY `id_2` (`id`,`id_forms`) ) TYPE=MyISAM AUTO_INCREMENT=155 ; -- -------------------------------------------------------- -- -- Table structure for table `dims_mod_forms_reply` -- DROP TABLE IF EXISTS `dims_mod_forms_reply`; CREATE TABLE IF NOT EXISTS `dims_mod_forms_reply` ( `id` int(10) unsigned NOT NULL auto_increment, `id_forms` int(10) unsigned default '0', `id_user` int(10) unsigned default '0', `id_workspace` tinyint(3) unsigned default '0', `id_module` int(10) unsigned default NULL, `date_validation` varchar(14) default NULL, `ip` varchar(15) default NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), KEY `id_2` (`id`) ) TYPE=MyISAM AUTO_INCREMENT=47 ; -- -------------------------------------------------------- -- -- Table structure for table `dims_mod_forms_reply_field` -- DROP TABLE IF EXISTS `dims_mod_forms_reply_field`; CREATE TABLE IF NOT EXISTS `dims_mod_forms_reply_field` ( `id_reply` int(10) unsigned default '0', `id_forms` int(10) unsigned default '0', `id_field` int(10) unsigned default '0', `value` longtext, `id_user` int(10) NOT NULL default '0', `id_workspace` int(10) NOT NULL default '0', `id_module` int(10) NOT NULL default '0', `id` int(10) NOT NULL auto_increment, `timestp_modify` bigint(14) NOT NULL default '0', PRIMARY KEY (`id`), KEY `id_reply` (`id_reply`), KEY `id_forms` (`id_forms`), KEY `id_field` (`id_field`), KEY `id_workspace` (`id_workspace`,`id_module`) ) TYPE=MyISAM AUTO_INCREMENT=355 ;
true
60e85fea5be649c01ee19ce48c5f0a51b01cfcbd
SQL
MARK-42/Store_Management
/tables.sql
UTF-8
2,490
3.578125
4
[]
no_license
DROP TABLE tabEmployee; DROP SEQUENCE employeeSeq; DROP TABLE tabCustomer; DROP SEQUENCE customerSeq; DROP TABLE tabBill; DROP SEQUENCE billSeq; DROP TABLE tabProductStock; DROP TABLE tabProductRegister; create table tabEmployee( employeeId number(4) NOT NULL PRIMARY KEY, firstName varchar2(15) NOT NULL, lastName varchar2(15) NOT NULL, username varchar2(15) NOT NULL UNIQUE, password varchar2(40) NOT NULL, phoneNumber number(11) NOT NULL UNIQUE, address varchar2(30) NOT NULL, email varchar2(20) NOT NULL UNIQUE, salary number(10) NOT NULL, isManager char(1) NOT NULL ); insert into tabEmployee values(1, 'owner', 'malik', 'USER', 'CF55D79929C2B5CDB13271782076FAAB487FADA0', 1234, 'addr', 'qwer', 0, 'Y'); CREATE SEQUENCE employeeSeq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10; create table tabCustomer( customerId number(10) NOT NULL PRIMARY KEY, firstName varchar2(15) NOT NULL, lastName varchar2(15) NOT NULL, phoneNumber number(11) NOT NULL UNIQUE, address varchar2(30) NOT NULL, email varchar2(20) NOT NULL UNIQUE, totalAmount number(15) DEFAULT 0 ); CREATE SEQUENCE customerSeq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10; create table tabBill( billId number(10) NOT NULL PRIMARY KEY, customerId number(4) NOT NULL, employeeId number(4) NOT NULL, amount number(10) NOT NULL, totalItems number(4) NOT NULL, paymentMethod varchar2(10) NOT NULL, billTime varchar2(20) NOT NULL, billDate varchar2(10) NOT NULL ); CREATE SEQUENCE billSeq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10; CREATE OR REPLACE TRIGGER afterBillInsert AFTER INSERT ON tabBill FOR EACH ROW BEGIN UPDATE tabCustomer SET totalAmount = totalAmount+:new.amount WHERE customerId = :new.customerId; dbms_output.put_line('Total Amount of customer with ID ' ||:new.customerId || ' updated.'); END; / create table tabProductStock( productId varchar2(20) NOT NULL PRIMARY KEY, productName varchar2(20) NOT NULL, catagory varchar2(20) NOT NULL, totalQuantity int NOT NULL, price float(2) NOT NULL, weight float(2) NOT NULL ); insert into tabProductStock values('A001', 'WASHING POWDER', 'TEST', 10, 20, 20); insert into tabProductStock values('A002', 'BRUSH', 'TEST', 20, 10, 5); create table tabProductRegister( productId varchar2(20) NOT NULL, billId number(10) NOT NULL, quantity int NOT NULL, sellPrice float(2) NOT NULL ); commit;
true
ab7377481cf4f8b6ec1aa2e11a6c4fb5087d1af7
SQL
ferkopar/ToDoSchema
/TREATM_REL_TAPI_1.sql
UTF-8
4,943
2.828125
3
[]
no_license
-------------------------------------------------------- -- DDL for Package Body TREATM_REL_TAPI -------------------------------------------------------- CREATE OR REPLACE PACKAGE BODY "TREATM_REL_TAPI" IS -- insert PROCEDURE ins( p_TREATM_ID2 IN TREATM_REL.TREATM_ID2%type , p_TIME_START IN TREATM_REL.TIME_START%type DEFAULT NULL , p_CRU IN TREATM_REL.CRU%type DEFAULT NULL , p_TREATM_ID1 IN TREATM_REL.TREATM_ID1%type , p_EXTRA_NEXT_STEP IN TREATM_REL.EXTRA_NEXT_STEP%type DEFAULT NULL , p_TO_DATE IN TREATM_REL.TO_DATE%type DEFAULT NULL , p_STATUS_ID IN TREATM_REL.STATUS_ID%type DEFAULT NULL , p_DESCRIPTION IN TREATM_REL.DESCRIPTION%type DEFAULT NULL , p_MDU IN TREATM_REL.MDU%type DEFAULT NULL , p_ORDER_NO IN TREATM_REL.ORDER_NO%type DEFAULT NULL , p_MM_ID IN TREATM_REL.MM_ID%type DEFAULT NULL , p_FROM_DATE IN TREATM_REL.FROM_DATE%type DEFAULT NULL , p_TREATM_REL_ID IN TREATM_REL.TREATM_REL_ID%type , p_REL_TYPE_ID IN TREATM_REL.REL_TYPE_ID%type , p_CRD IN TREATM_REL.CRD%type DEFAULT NULL , p_MDD IN TREATM_REL.MDD%type DEFAULT NULL , p_EPI_ID IN TREATM_REL.EPI_ID%type DEFAULT NULL , p_TIME_END IN TREATM_REL.TIME_END%type DEFAULT NULL , p_GO_ORDER_NO IN TREATM_REL.GO_ORDER_NO%type DEFAULT NULL , p_KOD1 IN TREATM_REL.KOD1%type DEFAULT NULL , p_KOD2 IN TREATM_REL.KOD2%type DEFAULT NULL ) IS BEGIN INSERT INTO TREATM_REL ( TREATM_ID2 , TIME_START , CRU , TREATM_ID1 , EXTRA_NEXT_STEP , TO_DATE , STATUS_ID , DESCRIPTION , MDU , ORDER_NO , MM_ID , FROM_DATE , TREATM_REL_ID , REL_TYPE_ID , CRD , MDD , EPI_ID , TIME_END , GO_ORDER_NO , KOD1 , KOD2 ) VALUES ( p_TREATM_ID2 , p_TIME_START , p_CRU , p_TREATM_ID1 , p_EXTRA_NEXT_STEP , p_TO_DATE , p_STATUS_ID , p_DESCRIPTION , p_MDU , p_ORDER_NO , p_MM_ID , p_FROM_DATE , p_TREATM_REL_ID , p_REL_TYPE_ID , p_CRD , p_MDD , p_EPI_ID , p_TIME_END , p_GO_ORDER_NO , p_KOD1 , p_KOD2 ); END; -- update PROCEDURE upd ( p_TREATM_ID2 IN TREATM_REL.TREATM_ID2%type , p_TIME_START IN TREATM_REL.TIME_START%type DEFAULT NULL , p_CRU IN TREATM_REL.CRU%type DEFAULT NULL , p_TREATM_ID1 IN TREATM_REL.TREATM_ID1%type , p_EXTRA_NEXT_STEP IN TREATM_REL.EXTRA_NEXT_STEP%type DEFAULT NULL , p_TO_DATE IN TREATM_REL.TO_DATE%type DEFAULT NULL , p_STATUS_ID IN TREATM_REL.STATUS_ID%type DEFAULT NULL , p_DESCRIPTION IN TREATM_REL.DESCRIPTION%type DEFAULT NULL , p_MDU IN TREATM_REL.MDU%type DEFAULT NULL , p_ORDER_NO IN TREATM_REL.ORDER_NO%type DEFAULT NULL , p_MM_ID IN TREATM_REL.MM_ID%type DEFAULT NULL , p_FROM_DATE IN TREATM_REL.FROM_DATE%type DEFAULT NULL , p_TREATM_REL_ID IN TREATM_REL.TREATM_REL_ID%type , p_REL_TYPE_ID IN TREATM_REL.REL_TYPE_ID%type , p_CRD IN TREATM_REL.CRD%type DEFAULT NULL , p_MDD IN TREATM_REL.MDD%type DEFAULT NULL , p_EPI_ID IN TREATM_REL.EPI_ID%type DEFAULT NULL , p_TIME_END IN TREATM_REL.TIME_END%type DEFAULT NULL , p_GO_ORDER_NO IN TREATM_REL.GO_ORDER_NO%type DEFAULT NULL , p_KOD1 IN TREATM_REL.KOD1%type DEFAULT NULL , p_KOD2 IN TREATM_REL.KOD2%type DEFAULT NULL ) IS BEGIN UPDATE TREATM_REL SET TREATM_ID2 = p_TREATM_ID2 , TIME_START = p_TIME_START , CRU = p_CRU , TREATM_ID1 = p_TREATM_ID1 , EXTRA_NEXT_STEP = p_EXTRA_NEXT_STEP , TO_DATE = p_TO_DATE , STATUS_ID = p_STATUS_ID , DESCRIPTION = p_DESCRIPTION , MDU = p_MDU , ORDER_NO = p_ORDER_NO , MM_ID = p_MM_ID , FROM_DATE = p_FROM_DATE , REL_TYPE_ID = p_REL_TYPE_ID , CRD = p_CRD , MDD = p_MDD , EPI_ID = p_EPI_ID , TIME_END = p_TIME_END , GO_ORDER_NO = p_GO_ORDER_NO , KOD1 = p_KOD1 , KOD2 = p_KOD2 WHERE TREATM_REL_ID = p_TREATM_REL_ID; END; -- del PROCEDURE del( p_TREATM_REL_ID IN TREATM_REL.TREATM_REL_ID%type ) IS BEGIN DELETE FROM TREATM_REL WHERE TREATM_REL_ID = p_TREATM_REL_ID; END; END TREATM_REL_tapi; /
true
1cda4dc3370c0ebb9c068d5abc538b81405b01fb
SQL
jrjr-randy/backoffice
/sql/proc/payout_rank_bonus.proc.sql
UTF-8
1,962
4.25
4
[]
no_license
-- -------------------------------------------------------------------------------- -- Commissions - Rank Bonus -- -------------------------------------------------------------------------------- DELIMITER $$ DROP PROCEDURE IF EXISTS `payout_rank_bonus`$$ CREATE PROCEDURE `payout_rank_bonus`(_commission_period_id INT) BEGIN SET @commission_payout_type_id = (SELECT commission_payout_type_id FROM commission_payout_types WHERE `name` = 'rank_bonus'); SET @total_rank_volume_type = (SELECT commission_value_type_id FROM commission_value_types WHERE NAME = 'total_rank_volume'); DELETE FROM commissions.current_commission_payouts WHERE commission_payout_type_id=@commission_payout_type_id; INSERT INTO commissions.current_commission_payouts ( `commission_payout_type_id`, `business_center_id`, `commission_period_id`, `value` ) SELECT @commission_payout_type_id,bc.business_center_id,_commission_period_id, IFNULL(( SELECT cr.value FROM commission_rank_bonus_rules cr WHERE cr.country_id = a.country_id AND cr.start_period <= _commission_period_id AND cr.up_to_rank_volume >= cv.value ORDER BY start_period DESC, up_to_rank_volume LIMIT 1 ),0) AS rank_bonus FROM business_centers bc JOIN distributors d USING(distributor_id) LEFT JOIN distributor_consumer_xref dcx ON d.distributor_id = dcx.consumer_id JOIN addresses a ON a.address_id = d.mailing_address_id JOIN commissions.current_commission_values cv ON cv.business_center_id = bc.business_center_id AND cv.commission_period_id = _commission_period_id AND cv.commission_value_type_id = @total_rank_volume_type WHERE bc.sequence = 1 AND dcx.consumer_id IS NULL AND 0 < get_current_business_level(bc.business_center_id) AND EXISTS(SELECT 1 FROM commission_rank_bonus_rules WHERE country_id = a.country_id AND start_period <= _commission_period_id); END$$ DELIMITER ;
true
d8df8571d2025ddf3b5dd64209b41587fd162391
SQL
ProfDema/uam
/pam/examples/anon_data/group_0088/q9.sql
UTF-8
506
3.625
4
[]
no_license
truncate query9; --[5 Marks] Report of sales by products introduced on or before 31 Dec 2015 and sort them in increasing order of the introduction date. A sale --is represented by a row of order table with status ‘S’. INSERT INTO query9 SELECT p.pid as pid, p.introdate as date, sum(o.quantity*o.price) as totalsales FROM orders o, product p WHERE o.pid = p.pid AND p.introdate >= '31 Dec 2015' AND o.status = 'S' GROUP BY p.pid, p.introdate ORDER BY date ASC; select * from query9;
true
c90736a610f801e167ddc5efb37860feb850606f
SQL
Swarmops/Swarmops
/Database/Schemata/upgrade-0075.sql
UTF-8
5,606
4
4
[ "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0", "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
CREATE TABLE `FinancialAccountDocuments` ( `FinancialAccountDocumentId` INT NOT NULL AUTO_INCREMENT, `FinancialAccountId` INT NOT NULL, `FinancialAccountDocumentTypeId` INT NOT NULL, `UploadedDateTime` DATETIME NOT NULL, `UploadedByPersonId` INT NOT NULL, `ConcernsPeriodStart` DATETIME NOT NULL, `ConcernsPeriodEnd` DATETIME NOT NULL, `RawDocumentText` TEXT NOT NULL, PRIMARY KEY (`FinancialAccountDocumentId`), INDEX `ixAccountId` (`FinancialAccountId` ASC), INDEX `ixDocType` (`FinancialAccountDocumentTypeId` ASC), INDEX `ixUploadedTime` (`UploadedDateTime` ASC), INDEX `ixUploadedPerson` (`UploadedByPersonId` ASC), INDEX `ixPeriod` (`ConcernsPeriodStart` ASC)) # CREATE TABLE `FinancialAccountDocumentTypes` ( `FinancialAccountDocumentTypeId` INT NOT NULL AUTO_INCREMENT, `Name` VARCHAR(128) NOT NULL, PRIMARY KEY (`FinancialAccountDocumentTypeId`), INDEX `ixName` (`Name` ASC)) # CREATE TABLE `FinancialTransactionRowImportHashes` ( `FinancialTransactionRowImportHashId` INT NOT NULL AUTO_INCREMENT, `FinancialTransactionRowId` INT NOT NULL, `FinancialAccountDocumentId` INT NOT NULL, `Sha256` VARCHAR(128) NOT NULL DEFAULT '', `ProvidedUniqueId` VARCHAR(512) NOT NULL DEFAULT '', PRIMARY KEY (`FinancialTransactionRowImportHashId`), INDEX `ixTransactionRow` (`FinancialTransactionRowId` ASC), INDEX `ixDocument` (`FinancialAccountDocumentId` ASC), INDEX `ixSha256` (`Sha256` ASC), INDEX `ixUniqueId` (`ProvidedUniqueId` ASC)) # DROP PROCEDURE IF EXISTS `CreateFinancialAccountDocument` # DROP PROCEDURE IF EXISTS `SetFinancialTransactionRowProvidedUniqueId` # DROP PROCEDURE IF EXISTS `SetFinancialTransactionRowImportSha256` # CREATE PROCEDURE `CreateFinancialAccountDocument`( IN financialAccountId INT, IN financialAccountDocumentType VARCHAR(128), IN uploadedDateTime DATETIME, IN uploadedByPersonId INT, IN concernsPeriodStart DATETIME, IN concernsPeriodEnd DATETIME, IN rawDocumentText TEXT ) BEGIN DECLARE documentTypeId INT; IF ((SELECT COUNT(*) FROM FinancialAccountDocumentTypes WHERE FinancialAccountDocumentTypes.Name=financialAccountDocumentType) = 0) THEN INSERT INTO FinancialAccountDocumentTypes(Name) VALUES (financialAccountDocumentType); SELECT LAST_INSERT_ID() INTO documentTypeId; ELSE SELECT FinancialAccountDocumentTypes.FinancialAccountDocumentTypeId INTO documentTypeId FROM FinancialAccountDocumentTypes WHERE FinancialAccountDocumentTypes.Name=financialAccountDocumentType; END IF; INSERT INTO FinancialAccountDocuments (FinancialAccountId,FinancialAccountDocumentTypeId,UploadedDateTime,UploadedByPersonId,ConcernsPeriodStart,ConcernsPeriodEnd,RawDocumentText) VALUES (financialAccountId,documentTypeId,uploadedDateTime,uploadedByPersonId,concernsPeriodStart,concernsPeriodEnd,rawDocumentText); SELECT LAST_INSERT_ID() AS Identity; END # CREATE PROCEDURE `SetFinancialTransactionRowProvidedUniqueId`( IN financialTransactionRowId INT, IN financialAccountDocumentId INT, IN providedUniqueId VARCHAR(512) ) BEGIN DECLARE recordId INT; IF ((SELECT COUNT(*) FROM FinancialTransactionRowImportHashes WHERE FinancialTransactionRowImportHashes.FinancialTransactionRowId=financialTransactionRowId AND FinancialTransactionRowImportHashes.FinancialAccountDocumentId=financialAccountDocumentId) = 0) THEN SELECT FinancialTransactionRowImportHashes.FinancialTransactionRowImportHashId INTO recordId FROM FinancialTransactionRowImportHashes WHERE FinancialTransactionRowImportHashes.FinancialTransactionRowId=financialTransactionRowId AND FinancialTransactionRowImportHashes.FinancialAccountDocumentId=financialAccountDocumentId; UPDATE FinancialTransactionRowImportHashes SET FinancialTransactionRowImportHashes.ProvidedUniqueId=providedUniqueId WHERE FinancialTransactionRowImportHashes.FinancialTransactionRowImportHashId=recordId; ELSE INSERT INTO FinancialTransactionRowImportHashes (FinancialTransactionRowId,FinancialAccountDocumentId,ProvidedUniqueId) VALUES (financialTransactionRowId,financialAccountDocumentId,providedUniqueId); SELECT LAST_INSERT_ID() INTO recordId; END IF; SELECT recordId AS Identity; END # CREATE PROCEDURE `SetFinancialTransactionRowImportSha256`( IN financialTransactionRowId INT, IN financialAccountDocumentId INT, IN sha256 VARCHAR(128) ) BEGIN DECLARE recordId INT; IF ((SELECT COUNT(*) FROM FinancialTransactionRowImportHashes WHERE FinancialTransactionRowImportHashes.FinancialTransactionRowId=financialTransactionRowId AND FinancialTransactionRowImportHashes.FinancialAccountDocumentId=financialAccountDocumentId) = 0) THEN SELECT FinancialTransactionRowImportHashes.FinancialTransactionRowImportHashId INTO recordId FROM FinancialTransactionRowImportHashes WHERE FinancialTransactionRowImportHashes.FinancialTransactionId=financialTransactionId AND FinancialTransactionRowImportHashes.FinancialAccountDocumentId=financialAccountDocumentId; UPDATE FinancialTransactionRowImportHashes SET FinancialTransactionRowImportHashes.Sha256=sha256 WHERE FinancialTransactionRowImportHashes.FinancialTransactionImportHashId=recordId; ELSE INSERT INTO FinancialTransactionRowImportHashes (FinancialTransactionId,FinancialAccountDocumentId,Sha256) VALUES (financialTransactionId,financialAccountDocumentId,sha256); SELECT LAST_INSERT_ID() INTO recordId; END IF; SELECT recordId AS Identity; END
true
a51c67f879f60902cee712277ebee3185f90ee0f
SQL
CollinJWynn/MySQLFinalProject
/newCreatedBy.sql
UTF-8
665
4.21875
4
[]
no_license
USE finalproject; DROP TABLE IF EXISTS CreatedBy; CREATE TABLE CreatedBy ( CreatedBy_ID int(11) NOT NULL auto_increment, CreatedBy VARCHAR(50) NOT NULL, PRIMARY KEY (CreatedBy_ID) ) AS SELECT DISTINCT CreatedBy FROM invoices WHERE CreatedBy IS NOT NULL ORDER BY CreatedBy; ALTER TABLE invoices ADD COLUMN CreatedBy_ID INT(11); UPDATE invoices INNER JOIN CreatedBy ON CreatedBy.CreatedBy = +invoices.CreatedBy SET invoices.CreatedBy_ID = CreatedBy.CreatedBy_ID WHERE CreatedBy.CreatedBy IS NOT NULL; SELECT inv.CreatedBy, inv.CreatedBy_ID, cb.CreatedBy FROM CreatedBy AS cb INNER JOIN invoices AS inv ON cb.CreatedBy_ID = inv.CreatedBy_ID;
true
9da380f708d1429c7501a100afbdc0eb43ace257
SQL
sebgatullah372/Perky_Rabbit_task
/perky_rabbit.sql
UTF-8
8,199
2.875
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Sep 22, 2020 at 10:12 AM -- Server version: 10.4.13-MariaDB -- PHP Version: 7.4.7 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 */; -- -- Database: `perky_rabbit` -- -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE `categories` ( `id` bigint(20) UNSIGNED NOT NULL, `category_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `status` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`id`, `category_name`, `status`, `created_at`, `updated_at`) VALUES (1, 'Cat1', 'stat1', '2020-09-22 00:18:32', '2020-09-22 00:18:32'); -- -------------------------------------------------------- -- -- Table structure for table `customers` -- CREATE TABLE `customers` ( `id` bigint(20) UNSIGNED NOT NULL, `cust_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `mobile` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `image` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `customers` -- INSERT INTO `customers` (`id`, `cust_id`, `name`, `email`, `mobile`, `image`, `created_at`, `updated_at`) VALUES (1, 'Arn472449', 'Arnob', '[email protected]', '01521212602', 'uploads_images/customers/16785179657235442020-09-22_07_24_33.png', '2020-09-22 01:24:33', '2020-09-22 01:24:33'); -- -------------------------------------------------------- -- -- Table structure for table `failed_jobs` -- CREATE TABLE `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL, `uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2014_10_12_000000_create_users_table', 1), (2, '2014_10_12_100000_create_password_resets_table', 1), (3, '2019_08_19_000000_create_failed_jobs_table', 1), (4, '2020_09_22_052356_create_customers_table', 1), (5, '2020_09_22_052945_create_products_table', 2), (6, '2020_09_22_053554_create_categories_table', 2), (7, '2020_09_22_072947_create_proposals_table', 3); -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` bigint(20) UNSIGNED NOT NULL, `product_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `SKU_id` text COLLATE utf8mb4_unicode_ci NOT NULL, `qty` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `price` double NOT NULL, `category_id` bigint(20) UNSIGNED NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `products` -- INSERT INTO `products` (`id`, `product_name`, `SKU_id`, `qty`, `price`, `category_id`, `created_at`, `updated_at`) VALUES (1, 'Motorcycle', '5f699ccb06232', '10', 250000, 1, '2020-09-22 00:42:19', '2020-09-22 00:42:19'); -- -------------------------------------------------------- -- -- Table structure for table `proposals` -- CREATE TABLE `proposals` ( `id` bigint(20) UNSIGNED NOT NULL, `proposal_number` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `ref_cust_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `issue_date` date NOT NULL, `ref_category_id` bigint(20) NOT NULL, `quantity` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `price` double NOT NULL, `discount` double NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Indexes for dumped tables -- -- -- Indexes for table `categories` -- ALTER TABLE `categories` ADD PRIMARY KEY (`id`); -- -- Indexes for table `customers` -- ALTER TABLE `customers` ADD PRIMARY KEY (`id`); -- -- Indexes for table `failed_jobs` -- ALTER TABLE `failed_jobs` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`id`); -- -- Indexes for table `proposals` -- ALTER TABLE `proposals` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `categories` -- ALTER TABLE `categories` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `customers` -- ALTER TABLE `customers` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `failed_jobs` -- ALTER TABLE `failed_jobs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `proposals` -- ALTER TABLE `proposals` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; 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
a598ce4f893b6fa788aba23a9985a3462da4554e
SQL
ouahsai/corot_enquetes
/_SQL/requeteCOUNT.sql
UTF-8
187
3.40625
3
[]
no_license
USE sondages; SELECT p.libelle, count(DISTINCT r.id) compte FROM proposition p LEFT JOIN reponse r ON r.id_proposition = p.id WHERE p.id_question = 4 GROUP BY p.id ORDER BY compte DESC;
true
e4cc00faee7774378a15c594ba57468f3301fa2d
SQL
asmgit/erp_example_sql
/assets/seed/test_data_documents.sql
UTF-8
5,860
3.65625
4
[]
no_license
SET @@cte_max_recursion_depth = 999999 ; SET @clients_count = 5000 , @materials_count = 50000 , @documents_count = 100000 , @positions_per_document = 150 ; SET FOREIGN_KEY_CHECKS = 0, SQL_LOG_BIN = 0, UNIQUE_CHECKS = 0 ; TRUNCATE TABLE current_stock; TRUNCATE TABLE document_positions; TRUNCATE TABLE documents; TRUNCATE TABLE materials; TRUNCATE TABLE organizations; TRUNCATE TABLE document_types; INSERT document_types (id, credit_type, name) VALUES (1, 1, 'Отгрузка покупателю') , (2, -1, 'Приход от поставщика') , (6, 0, 'ЗПС') , (8, 0, 'План производства') ; INSERT organizations (type, name) VALUES ('address', 'Склад 1') , ('address', 'Склад 2') , ('address', 'Склад 3') , ('address', 'Склад 4') , ('ur', 'Юрлицо 1') , ('ur', 'Юрлицо 2') , ('ur', 'Юрлицо 3') , ('manufacturer', 'Производитель 1') , ('manufacturer', 'Производитель 2') , ('manufacturer', 'Производитель 3') , ('manufacturer', 'Производитель 4') , ('manufacturer', 'Производитель 5') , ('manufacturer', 'Производитель 6') , ('manufacturer', 'Производитель 7') , ('manufacturer', 'Производитель 8') , ('manufacturer', 'Производитель 9') , ('manufacturer', 'Производитель 10') , ('manufacturer', 'Производитель 11') ; INSERT organizations (type, name) WITH RECURSIVE p(n) AS ( SELECT 1 n UNION ALL SELECT n + 1 n FROM p WHERE n + 1 <= @clients_count ) SELECT 'client', CONCAT('Клиент ', p.n) name FROM p ; SELECT MIN(IF(type = 'address', id, NULL)) min_address_id , MAX(IF(type = 'address', id, NULL)) max_address_id , MIN(IF(type = 'ur', id, NULL)) min_ur_id , MAX(IF(type = 'ur', id, NULL)) max_ur_id , MIN(IF(type = 'manufacturer', id, NULL)) min_manufacturer_id , MAX(IF(type = 'manufacturer', id, NULL)) max_manufacturer_id , MIN(IF(type = 'client', id, NULL)) min_client_id , MAX(IF(type = 'client', id, NULL)) max_client_id FROM organizations INTO @min_address_id , @max_address_id , @min_ur_id , @max_ur_id , @min_manufacturer_id , @max_manufacturer_id , @min_client_id , @max_client_id ; INSERT materials (name, organization_id_manufacturer) WITH RECURSIVE p(n) AS ( SELECT 1 n UNION ALL SELECT n + 1 n FROM p WHERE n + 1 <= @materials_count ) SELECT CONCAT('Товар ', n) name , FLOOR(@min_manufacturer_id + (RAND() * (@max_manufacturer_id - @min_manufacturer_id + 1))) organization_id_manufacturer FROM p ; INSERT documents (date, document_type_id, organization_id_address, organization_id_ur, organization_id_client, closed) WITH RECURSIVE p(n, date) AS ( SELECT 1 n , DATE(NOW() - INTERVAL FLOOR(0 + (RAND() * 365)) DAY) date UNION ALL SELECT n + 1 n , DATE(NOW() - INTERVAL FLOOR(0 + (RAND() * 365)) DAY) date FROM p WHERE n + 1 <= @documents_count ) SELECT date , CASE FLOOR(1 + (RAND() * 4)) WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 6 WHEN 4 THEN 8 END document_type_id , FLOOR(@min_address_id + (RAND() * (@max_address_id - @min_address_id + 1))) organization_id_address , FLOOR(@min_ur_id + (RAND() * (@max_ur_id - @min_ur_id + 1))) organization_id_ur , FLOOR(@min_client_id + (RAND() * (@max_client_id - @min_client_id + 1))) organization_id_client , IF(date < DATE(NOW() - INTERVAL 30 DAY), 1, 0) FROM p ; ALTER TABLE document_positions DROP CONSTRAINT document_positions_document_id , DROP CONSTRAINT document_positions_material_id , DROP KEY document_id , DROP KEY material_id ; INSERT document_positions (document_id, material_id, cnt) WITH RECURSIVE p(n) AS ( SELECT 1 n UNION ALL SELECT n + 1 n FROM p WHERE n + 1 <= @positions_per_document ) , d AS ( SELECT d.id document_id , FLOOR(1 + (RAND() * @materials_count)) material_id FROM p CROSS JOIN documents d ) SELECT document_id, material_id , FLOOR(1 + (RAND() * 1000)) cnt FROM d ; ALTER TABLE document_positions ADD KEY (document_id, material_id, cnt) ; ALTER TABLE document_positions ADD KEY (material_id) ; ALTER TABLE document_positions ADD CONSTRAINT document_positions_document_id FOREIGN KEY (document_id) REFERENCES documents (id) ; ALTER TABLE document_positions ADD CONSTRAINT document_positions_material_id FOREIGN KEY (material_id) REFERENCES materials (id) ; ALTER TABLE current_stock DROP CONSTRAINT current_stock_material_id , DROP CONSTRAINT current_stock_organization_id_address , DROP CONSTRAINT current_stock_organization_id_ur , DROP KEY current_stock_material_id , DROP KEY current_stock_organization_id_ur ; INSERT INTO current_stock (organization_id_address, organization_id_ur, material_id, cnt, reserve) SELECT d.organization_id_address, d.organization_id_ur, dp.material_id , SUM(IF(d.closed = 1, IFNULL(dp.cnt, 0) * t.credit_type * -1, 0)) cnt , SUM(IF(d.closed = 1, 0, IFNULL(dp.cnt, 0) * IF(t.credit_type = 1, 1, 0))) reserve FROM documents d INNER JOIN document_positions dp ON d.id = dp.document_id INNER JOIN document_types t ON d.document_type_id = t.id WHERE IFNULL(dp.cnt, 0) != 0 AND t.credit_type IN (-1, 1) GROUP BY d.organization_id_address, d.organization_id_ur, dp.material_id HAVING cnt != 0 OR reserve != 0 ; ALTER TABLE current_stock ADD KEY current_stock_material_id (material_id) ; ALTER TABLE current_stock ADD KEY current_stock_organization_id_ur (organization_id_ur) ; ALTER TABLE current_stock ADD CONSTRAINT current_stock_organization_id_address FOREIGN KEY (organization_id_address) REFERENCES organizations (id) ; ALTER TABLE current_stock ADD CONSTRAINT current_stock_organization_id_ur FOREIGN KEY (organization_id_ur) REFERENCES organizations (id) ; ALTER TABLE current_stock ADD CONSTRAINT current_stock_material_id FOREIGN KEY (material_id) REFERENCES materials (id) ; SET FOREIGN_KEY_CHECKS = 1, SQL_LOG_BIN = 1, UNIQUE_CHECKS = 1 ;
true
94b79d019757103f16c5aa36e32e23ae93078930
SQL
JuanMtz/Examen-2da-oportunidad
/examen2_juanAntonio.sql
UTF-8
14,401
3.234375
3
[]
no_license
-- MySQL Script generated by MySQL Workbench -- 05/07/15 18:59:44 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; -- ----------------------------------------------------- -- Schema restaurante -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema restaurante -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `restaurante` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; USE `restaurante` ; -- ----------------------------------------------------- -- Table `restaurante`.`entrada` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`entrada` ( `identrada` INT NOT NULL, `Entrada` VARCHAR(45) NULL, `precio` DOUBLE NULL, PRIMARY KEY (`identrada`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`Platillo_Fuerte` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`Platillo_Fuerte` ( `idplatillo` INT NOT NULL, `Platillo fuerte` VARCHAR(45) NULL, `precio` DOUBLE NULL, PRIMARY KEY (`idplatillo`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`bebidas` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`bebidas` ( `idbebida` INT NOT NULL, `Bebida` VARCHAR(45) NULL, `precio` DOUBLE NULL, PRIMARY KEY (`idbebida`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`postres` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`postres` ( `idpostre` INT NOT NULL, `Postre` VARCHAR(45) NULL, `precio` DOUBLE NULL, PRIMARY KEY (`idpostre`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`Adicionales` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`Adicionales` ( `idadicional` INT NOT NULL, `Adicionales` VARCHAR(45) NULL, `precio` DOUBLE NULL, PRIMARY KEY (`idadicional`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`estatus` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`estatus` ( `idtipoS` INT NOT NULL, `Estatus` VARCHAR(45) NULL, PRIMARY KEY (`idtipoS`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`Mesa` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`Mesa` ( `idMesa` INT NOT NULL, `no_mesa` VARCHAR(45) NULL, `orden_idorden` INT NOT NULL, PRIMARY KEY (`idMesa`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`cliente` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`cliente` ( `idcliente` INT NOT NULL, `Nombre` VARCHAR(45) NULL, `Mesa_idMesa` INT NOT NULL, PRIMARY KEY (`idcliente`), INDEX `fk_cliente_Mesa1_idx` (`Mesa_idMesa` ASC), CONSTRAINT `fk_cliente_Mesa1` FOREIGN KEY (`Mesa_idMesa`) REFERENCES `restaurante`.`Mesa` (`idMesa`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`orden` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`orden` ( `idorden` INT NOT NULL, `cliente_idcliente` INT NOT NULL, `postres_idpostre` INT NOT NULL, `entrada_identrada` INT NOT NULL, `Platillo_Fuerte_idplatillo` INT NOT NULL, `bebidas_idbebida` INT NOT NULL, `Adicionales_idadicional` INT NOT NULL, `estatus_idtipoS` INT NOT NULL, `cantidad de personas` VARCHAR(45) NULL, PRIMARY KEY (`idorden`), INDEX `fk_orden_cliente1_idx` (`cliente_idcliente` ASC), INDEX `fk_orden_postres1_idx` (`postres_idpostre` ASC), INDEX `fk_orden_entrada1_idx` (`entrada_identrada` ASC), INDEX `fk_orden_Platillo_Fuerte1_idx` (`Platillo_Fuerte_idplatillo` ASC), INDEX `fk_orden_bebidas1_idx` (`bebidas_idbebida` ASC), INDEX `fk_orden_Adicionales1_idx` (`Adicionales_idadicional` ASC), INDEX `fk_orden_estatus1_idx` (`estatus_idtipoS` ASC), CONSTRAINT `fk_orden_cliente1` FOREIGN KEY (`cliente_idcliente`) REFERENCES `restaurante`.`cliente` (`idcliente`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_orden_postres1` FOREIGN KEY (`postres_idpostre`) REFERENCES `restaurante`.`postres` (`idpostre`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_orden_entrada1` FOREIGN KEY (`entrada_identrada`) REFERENCES `restaurante`.`entrada` (`identrada`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_orden_Platillo_Fuerte1` FOREIGN KEY (`Platillo_Fuerte_idplatillo`) REFERENCES `restaurante`.`Platillo_Fuerte` (`idplatillo`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_orden_bebidas1` FOREIGN KEY (`bebidas_idbebida`) REFERENCES `restaurante`.`bebidas` (`idbebida`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_orden_Adicionales1` FOREIGN KEY (`Adicionales_idadicional`) REFERENCES `restaurante`.`Adicionales` (`idadicional`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_orden_estatus1` FOREIGN KEY (`estatus_idtipoS`) REFERENCES `restaurante`.`estatus` (`idtipoS`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`factura` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`factura` ( `idfactura` INT NOT NULL, `cliente_idcliente` INT NOT NULL, `orden_idorden` INT NOT NULL, PRIMARY KEY (`idfactura`), INDEX `fk_factura_cliente1_idx` (`cliente_idcliente` ASC), INDEX `fk_factura_orden1_idx` (`orden_idorden` ASC), CONSTRAINT `fk_factura_cliente1` FOREIGN KEY (`cliente_idcliente`) REFERENCES `restaurante`.`cliente` (`idcliente`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_factura_orden1` FOREIGN KEY (`orden_idorden`) REFERENCES `restaurante`.`orden` (`idorden`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `restaurante`.`ornedes_mesa` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `restaurante`.`ornedes_mesa` ( `orden_idorden` INT NOT NULL, `Mesa_idMesa` INT NOT NULL, PRIMARY KEY (`orden_idorden`, `Mesa_idMesa`), INDEX `fk_orden_has_Mesa_Mesa1_idx` (`Mesa_idMesa` ASC), INDEX `fk_orden_has_Mesa_orden1_idx` (`orden_idorden` ASC), CONSTRAINT `fk_orden_has_Mesa_orden1` FOREIGN KEY (`orden_idorden`) REFERENCES `restaurante`.`orden` (`idorden`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_orden_has_Mesa_Mesa1` FOREIGN KEY (`Mesa_idMesa`) REFERENCES `restaurante`.`Mesa` (`idMesa`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('1', 'refresco al tiempo', '10'); INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('2', 'agual al tiempo', '5'); INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('3', 'cerveza al tiempo', '15'); INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('4', 'refresco frio', '15'); INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('5', 'agura fria', '10'); INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('6', 'cerveza fria', '25'); INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('7', 'refresco con hielo', '30'); INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('8', 'agua con hielo', '25'); INSERT INTO `restaurante`.`bebidas` (`idbebida`, `Bebida`, `precio`) VALUES ('9', 'cerveza con hielo', '40'); INSERT INTO `restaurante`.`postres` (`idpostre`, `Postre`, `precio`) VALUES ('1', 'flan napo', '20'); INSERT INTO `restaurante`.`postres` (`idpostre`, `Postre`, `precio`) VALUES ('2', 'pastel 3 leche', '30'); INSERT INTO `restaurante`.`postres` (`idpostre`, `Postre`, `precio`) VALUES ('3', 'copa helado', '20'); INSERT INTO `restaurante`.`postres` (`idpostre`, `Postre`, `precio`) VALUES ('4', 'copa fruta', '15'); INSERT INTO `restaurante`.`estatus` (`idtipoS`, `Estatus`) VALUES ('1', 'capturada'); INSERT INTO `restaurante`.`estatus` (`idtipoS`, `Estatus`) VALUES ('2', 'preparacion Estatus'); INSERT INTO `restaurante`.`estatus` (`idtipoS`, `Estatus`) VALUES ('3', 'enrada lista'); INSERT INTO `restaurante`.`estatus` (`idtipoS`, `Estatus`) VALUES ('4', 'prepacion plaoto fuerte'); INSERT INTO `restaurante`.`estatus` (`idtipoS`, `Estatus`) VALUES ('5', 'p fuerte listo'); INSERT INTO `restaurante`.`estatus` (`idtipoS`, `Estatus`) VALUES ('6', 'prepacion Estatus'); INSERT INTO `restaurante`.`estatus` (`idtipoS`, `Estatus`) VALUES ('7', 'Estatus listo'); INSERT INTO `restaurante`.`estatus` (`idtipoS`, `Estatus`) VALUES ('8', 'pagada'); INSERT INTO `restaurante`.`platillo_fuerte` (`idplatillo`, `Platillo fuerte`, `precio`) VALUES ('1', 'pollo sin picante', '100'); INSERT INTO `restaurante`.`platillo_fuerte` (`idplatillo`, `Platillo fuerte`, `precio`) VALUES ('2', 'pollo poco picante', '150'); INSERT INTO `restaurante`.`platillo_fuerte` (`idplatillo`, `Platillo fuerte`, `precio`) VALUES ('3', 'pollo muy picante', '200'); INSERT INTO `restaurante`.`platillo_fuerte` (`idplatillo`, `Platillo fuerte`, `precio`) VALUES ('4', 'carne sin picante', '150'); INSERT INTO `restaurante`.`platillo_fuerte` (`idplatillo`, `Platillo fuerte`, `precio`) VALUES ('5', 'carne poco picante', '200'); INSERT INTO `restaurante`.`platillo_fuerte` (`idplatillo`, `Platillo fuerte`, `precio`) VALUES ('6', 'carne muy picante', '250'); INSERT INTO `restaurante`.`adicionales` (`idadicional`, `Adicionales`, `precio`) VALUES ('1', 'arroz', '20'); INSERT INTO `restaurante`.`adicionales` (`idadicional`, `Adicionales`, `precio`) VALUES ('2', 'frijoles', '20'); INSERT INTO `restaurante`.`adicionales` (`idadicional`, `Adicionales`, `precio`) VALUES ('3', 'elotes', '10'); INSERT INTO `restaurante`.`adicionales` (`idadicional`, `Adicionales`, `precio`) VALUES ('4', 'verduras ', '15'); INSERT INTO `restaurante`.`adicionales` (`idadicional`, `Adicionales`, `precio`) VALUES ('5', 'papas fritas', '35'); INSERT INTO `restaurante`.`adicionales` (`idadicional`, `Adicionales`, `precio`) VALUES ('6', 'ninguno', '0'); INSERT INTO `restaurante`.`entrada` (`identrada`, `Entrada`, `precio`) VALUES ('1', 'arroz con frijoles', '30'); INSERT INTO `restaurante`.`entrada` (`identrada`, `Entrada`, `precio`) VALUES ('2', 'verduras con elote', '20'); INSERT INTO `restaurante`.`entrada` (`identrada`, `Entrada`, `precio`) VALUES ('3', 'papas fritas', '25'); ALTER TABLE `restaurante`.`cliente` DROP FOREIGN KEY `fk_cliente_Mesa1`; ALTER TABLE `restaurante`.`cliente` DROP COLUMN `Mesa_idMesa`, DROP INDEX `fk_cliente_Mesa1_idx` ; INSERT INTO `restaurante`.`cliente` (`idcliente`, `Nombre`) VALUES ('1', 'Juan'); INSERT INTO `restaurante`.`cliente` (`idcliente`, `Nombre`) VALUES ('2', 'Nadia'); INSERT INTO `restaurante`.`cliente` (`idcliente`, `Nombre`) VALUES ('3', 'Alan'); INSERT INTO `restaurante`.`mesa` (`idMesa`, `no_mesa`, `orden_idorden`) VALUES ('1', '1', '1'); INSERT INTO `restaurante`.`mesa` (`idMesa`, `no_mesa`, `orden_idorden`) VALUES ('2', '2', '2'); INSERT INTO `restaurante`.`mesa` (`idMesa`, `no_mesa`, `orden_idorden`) VALUES ('3', '3', '3'); INSERT INTO `restaurante`.`orden` (`idorden`, `cliente_idcliente`, `postres_idpostre`, `entrada_identrada`, `Platillo_Fuerte_idplatillo`, `bebidas_idbebida`, `Adicionales_idadicional`, `estatus_idtipoS`, `cantidad de personas`) VALUES ('1', '1', '3', '2', '4', '5', '1', '1', '1'); INSERT INTO `restaurante`.`orden` (`idorden`, `cliente_idcliente`, `postres_idpostre`, `entrada_identrada`, `Platillo_Fuerte_idplatillo`, `bebidas_idbebida`, `Adicionales_idadicional`, `estatus_idtipoS`, `cantidad de personas`) VALUES ('2', '2', '2', '2', '5', '4', '1', '1', '1'); INSERT INTO `restaurante`.`orden` (`idorden`, `cliente_idcliente`, `postres_idpostre`, `entrada_identrada`, `Platillo_Fuerte_idplatillo`, `bebidas_idbebida`, `Adicionales_idadicional`, `estatus_idtipoS`, `cantidad de personas`) VALUES ('3', '3', '1', '1', '2', '1', '2', '1', '1'); INSERT INTO `restaurante`.`ornedes_mesa` (`orden_idorden`, `Mesa_idMesa`) VALUES ('1', '1'); INSERT INTO `restaurante`.`ornedes_mesa` (`orden_idorden`, `Mesa_idMesa`) VALUES ('2', '1'); INSERT INTO `restaurante`.`ornedes_mesa` (`orden_idorden`, `Mesa_idMesa`) VALUES ('3', '1'); ALTER TABLE `restaurante`.`factura` DROP FOREIGN KEY `fk_factura_orden1`; ALTER TABLE `restaurante`.`factura` CHANGE COLUMN `orden_idorden` `Mesa_idMesa` INT(11) NOT NULL ; ALTER TABLE `restaurante`.`factura` ADD CONSTRAINT `fk_factura_idmesa` FOREIGN KEY (`Mesa_idMesa`) REFERENCES `restaurante`.`mesa` (`idmesa`) ON DELETE NO ACTION ON UPDATE NO ACTION; INSERT INTO `restaurante`.`factura` (`idfactura`, `cliente_idcliente`, `Mesa_idMesa`) VALUES ('1', '1', '1'); ALTER TABLE `restaurante`.`platillo_fuerte` RENAME TO `restaurante`.`platillo` ; ALTER TABLE `restaurante`.`platillo` CHANGE COLUMN `Platillo fuerte` `Platillo` VARCHAR(45) NULL DEFAULT NULL ; select e.Entrada, f.Platillo, b.Bebida, p.Postre, a.Adicionales, c.Nombre, (e.precio+f.precio+b.precio+p.precio+a.precio) as total from entrada e inner join platillo f on e.identrada=f.idplatillo inner join bebidas b on f.idplatillo=b.idbebida inner join postres p on b.idbebida=p.idpostre inner join cliente c on p.idpostre=c.idcliente inner join adicionales a on c.idcliente=a.idadicional
true
5086ddf1a839e242bb69d1c38e3044d2b91a3ca1
SQL
gpereiraPy/Paddle
/BD.sql
UTF-8
1,918
3.46875
3
[]
no_license
create database paddle; create table usuarios ( id_usuario int not null primary key AUTO_INCREMENT, nombre varchar(50) not null, edad char(4) not null, email varchar(40), telefono char(15), direccion varchar(60) ); create table cancha ( id_cancha int not null primary key AUTO_INCREMENT, precio DECIMAL(7,2) not null, descripcion varchar(30) ); create table alquiler ( alquiler_id int not null primary key AUTO_INCREMENT, id_cancha int not null, id_usuario int not null, fecha date not null, hora time not null, cant_hora int not null ); alter table alquiler ADD UNIQUE (hora); alter table alquiler add column hora_hasta time not null; alter table usuarios ADD UNIQUE (email); insert into usuarios (nombre, edad, email, telefono, direccion) values ('Guido Pereira','33','[email protected]','0981525201', 'Villa Aurelia. Asuncion'); insert into usuarios (nombre, edad, email, telefono, direccion) values ('Abel Pereira','35','[email protected]','0983603576', 'Santa Ana. CDE'); insert into usuarios (nombre, edad, email, telefono, direccion) values ('Rene Pereira','31','[email protected]','0981589754', 'Santa Ana. CDE'); insert into usuarios (nombre, edad, email, telefono, direccion) values ('Aldo Pereira','29','[email protected]','0985897541', 'Santa Ana. CDE'); insert into cancha (precio, descripcion) values (40000, 'techada con luminica'); insert into cancha (precio, descripcion) values (40000, 'techada con luminica'); insert into cancha (precio, descripcion) values (30000, 'sin techo con luminica'); insert into cancha (precio, descripcion) values (30000, 'sin techo con luminica'); insert into alquiler (id_cancha, id_usuario, fecha, hora, cant_hora) values (1,1, '2015-10-10','16:00:00',2); insert into alquiler (id_cancha, id_usuario, fecha, hora, cant_hora) values (2,2, '2015-10-10','16:00:00',1); insert into alquiler (id_cancha, id_usuario, fecha, hora, cant_hora) values (3,3, '2015-10-10','16:00:00',1);
true
d68ae408d6129e3051cac07377f481f3ab9133f3
SQL
mscheck-mscs/1714mscheckV
/1714mscheck2F2/1417mscheck2f2.sql
UTF-8
1,501
3.96875
4
[]
no_license
--Miranda Scheck --EX: 2F quries --Animal Shelter --1) All Animals SELECT Animals.AnimalName, AnimalTypes.Type, People.FirstName + N' ' + People.LastName AS Owner FROM Animals INNER JOIN AnimalTypes ON Animals.AnimalType_Id = AnimalTypes.Id INNER JOIN People ON Animals.Person_Id = People.Id --2)Cash Donation SELECT People.LastName + N', ' + People.FirstName AS Donor, Donations.DonationDate, Donations.Value AS Amount FROM People INNER JOIN Donations ON People.Id = Donations.Person_Id INNER JOIN DonationTypes ON Donations.DonationType_Id = DonationTypes.Id WHERE (DonationTypes.Description = N'cash') --3) TotalDonations for each SELECT People.Id, People.FirstName + N' ' + People.LastName AS Donor, SUM(Donations.Value) AS [Total Donations] FROM Donations INNER JOIN People ON Donations.Person_Id = People.Id GROUP BY People.FirstName + N' ' + People.LastName, People.Id --4) Number of dogs for each owner SELECT People.Id, People.LastName + N', ' + People.FirstName AS Owner, SUM(AnimalTypes.Id) AS [Number of Dogs] FROM People INNER JOIN Animals ON People.Id = Animals.Person_Id INNER JOIN AnimalTypes ON Animals.AnimalType_Id = AnimalTypes.Id GROUP BY People.Id, People.LastName + N', ' + People.FirstName HAVING (SUM(AnimalTypes.Id) = 1)
true
97daac1ba059794dee202e2fd538d9b8101d6ca6
SQL
lyoshik11111993/auction_house
/auctionhouse.sql
UTF-8
1,341
3.921875
4
[]
no_license
CREATE TABLE `Seller` ( `id` int(11) unsigned NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 CREATE TABLE `product` ( `id` int(11) unsigned NOT NULL, `name` varchar(255) NOT NULL, `seller_id` int(11) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_product_seller_idx_idx` (`seller_id`), CONSTRAINT `fk_product_seller_idx` FOREIGN KEY (`seller_id`) REFERENCES `Seller` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8 CREATE TABLE `Buyer` ( `id` int(11) unsigned NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 CREATE TABLE `bid` ( `id` int(11) unsigned NOT NULL, `name` varchar(255) NOT NULL, `date_of_sale` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `product_id` int(11) unsigned DEFAULT NULL, `buyer_id` int(11) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_bid_product_idx_idx` (`product_id`), KEY `fk_bid_buyer_idx_idx` (`buyer_id`), CONSTRAINT `fk_bid_buyer_idx` FOREIGN KEY (`buyer_id`) REFERENCES `Buyer` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_bid_product_idx` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8
true
e0775c8f4f2b34728a10855f90872dbf3325581b
SQL
abaker4/grocery-list
/bootstrap.sql
UTF-8
688
3.09375
3
[]
no_license
CREATE DATABASE grocerylist; use grocerylist; CREATE TABLE `list` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(355) DEFAULT NULL, `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `item` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(355) DEFAULT NULL, `quantity` int(11) DEFAULT NULL, `fulfilled` tinyint(4) DEFAULT '0', `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NULL DEFAULT NULL, `list` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
true
d1dc9437339a15300b2c489125601ab85074e439
SQL
dsoccer1980/spring-db
/jpa/spring-boot-jpa/src/main/resources/data.sql
UTF-8
475
2.515625
3
[]
no_license
DELETE FROM Book; DELETE FROM Author; INSERT INTO Author(id, name) VALUES (1, 'Стругацкий'); INSERT INTO Author(id, name) VALUES (2, 'Уэллс'); INSERT INTO Author(id, name) VALUES (3, 'Пушкин'); INSERT INTO Book(id, name, author_id) VALUES (100, 'Трудно быть Богом', 1); INSERT INTO Book(id, name, author_id) VALUES (101, 'Машина времени', 2); INSERT INTO Book(id, name, author_id) VALUES (102, 'Онегин', 3);
true
2517880db68a91963eee57e96e4ec0515b140c63
SQL
ICE-SIB/sib
/sql/V3__fix_rate_type.sql
UTF-8
316
2.984375
3
[ "MIT" ]
permissive
ALTER TABLE machine_deployments DROP COLUMN rate_type; ALTER TABLE machine_deployments DROP CONSTRAINT location; ALTER TABLE machines RENAME COLUMN code TO asset_number; ALTER TABLE machines ADD COLUMN rate_type char(1) NOT NULL; ALTER TABLE machines ADD CONSTRAINT valid_rate_type CHECK (rate_type IN ('h', 'd'));
true
72c54220fe4148c6b24bc30d29a14b30a08b7aa9
SQL
reiya-shioda/takuma-b
/mydb.sql
UTF-8
2,565
3.21875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 2017 年 7 朁E20 日 05:49 -- サーバのバージョン: 10.1.16-MariaDB -- PHP Version: 5.6.24 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: `mydb` -- -- -------------------------------------------------------- -- -- テーブルの構造 `menu` -- CREATE TABLE `menu` ( `id` int(5) NOT NULL, `menuname` varchar(20) CHARACTER SET utf8 NOT NULL, `calorie` int(10) NOT NULL, `size` varchar(20) NOT NULL, `material` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- テーブルのデータのダンプ `menu` -- INSERT INTO `menu` (`id`, `menuname`, `calorie`, `size`, `material`) VALUES (1, '牛丼', 708, '', ''), (2, '海鮮丼', 717, '', ''), (3, '中華丼', 661, '', ''), (4, '天丼', 551, '', ''), (5, 'そば', 332, '', ''), (6, 'うどん', 284, '', ''), (7, 'ラーメン', 500, '', ''), (8, 'ミートソース', 768, '', ''), (9, 'ハンバーガー', 308, '', ''), (10, 'フライドポテト', 249, '', ''), (11, 'チキンナゲット', 215, '', ''), (12, 'ホットケーキ', 564, '', ''), (13, '〆さば', 109, '', ''), (14, 'コーン', 231, '', ''), (15, 'ツナサラダ', 179, '', ''), (16, 'マグロ', 177, '', ''), (17, 'アンパン', 221, '', ''), (18, '食パン', 129, '', ''), (19, 'カレーパン', 350, '', ''), (20, 'クリームパン', 216, '', ''); -- -------------------------------------------------------- -- -- テーブルの構造 `userdata` -- CREATE TABLE `userdata` ( `id` int(5) NOT NULL, `name` varchar(20) CHARACTER SET utf8 NOT NULL, `password` varchar(100) NOT NULL, `gender` varchar(10) NOT NULL, `height` float NOT NULL, `weight` float NOT NULL DEFAULT '60' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `menu` -- ALTER TABLE `menu` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `menu` -- ALTER TABLE `menu` MODIFY `id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21; /*!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
4f5c053730dfe3342a4a5a400cefe7175f37d434
SQL
lyrric/config-server
/server/src/main/resources/sql/config_server.sql
UTF-8
2,078
3.09375
3
[]
no_license
/* Navicat MySQL Data Transfer Source Server : localhost_1 Source Server Version : 50640 Source Host : localhost:3306 Source Database : config_server Target Server Type : MYSQL Target Server Version : 50640 File Encoding : 65001 Date: 2020-04-29 10:33:31 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for config -- ---------------------------- DROP TABLE IF EXISTS `config`; CREATE TABLE `config` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `group_id` varchar(200) DEFAULT NULL, `data_id` varchar(200) DEFAULT NULL, `content` text, `created_time` datetime DEFAULT NULL COMMENT '创建时间', `modified_time` datetime DEFAULT NULL COMMENT '修改时间', PRIMARY KEY (`id`), KEY `group_id` (`group_id`), KEY `data_id` (`data_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='配置表'; -- ---------------------------- -- Records of config -- ---------------------------- INSERT INTO `config` VALUES ('1', 'test_group', 'test_data1', 'test.value=2001', '2019-03-13 14:10:06', '2019-03-22 09:53:11'); INSERT INTO `config` VALUES ('2', 'test_group', 'test_data2', 'test.name=haha', '2019-03-16 10:08:14', '2019-03-16 10:08:17'); -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) NOT NULL COMMENT '用户名', `password` varchar(50) DEFAULT NULL COMMENT '密码', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='用户表'; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'admin', '21232f297a57a5a743894a0e4a801fc3');
true
3787c2081df2dbb2e91ab5621ea6766a607b3d86
SQL
R4zi4l/smart-notes-trial
/database/setup.sql
UTF-8
13,478
3.828125
4
[]
no_license
CREATE TABLE `owner` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `table` VARCHAR(255) CHARACTER SET ascii NOT NULL, PRIMARY KEY(`id`) ); CREATE TABLE `session` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `owner` CHAR(36) CHARACTER SET ascii DEFAULT NULL, `updated` DATETIME(3) NOT NULL, `started` DATETIME NOT NULL, `expired` DATETIME NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`owner`) REFERENCES `owner`(`id`) ON DELETE CASCADE ); CREATE TABLE `settings` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `owner` CHAR(36) CHARACTER SET ascii NOT NULL, `device` VARCHAR(4096) NOT NULL, `updated` DATETIME(3) NOT NULL, `settings` TEXT, PRIMARY KEY(`id`), FOREIGN KEY(`owner`) REFERENCES `owner`(`id`) ON DELETE CASCADE ); CREATE TABLE `user` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `updated` DATETIME(3) NOT NULL, `email` VARCHAR(255) NOT NULL, `username` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`id`) REFERENCES `owner`(`id`) ON DELETE CASCADE ); CREATE TABLE `user_history` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `updated` DATETIME(3) NOT NULL, `action` VARCHAR(255) NOT NULL, `email` VARCHAR(255) DEFAULT NULL, `username` VARCHAR(255) DEFAULT NULL, `password` VARCHAR(255) DEFAULT NULL, PRIMARY KEY(`id`, `updated`), FOREIGN KEY(`id`) REFERENCES `owner`(`id`) ON DELETE CASCADE ); CREATE TABLE `entity` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `owner` CHAR(36) CHARACTER SET ascii NOT NULL, `table` VARCHAR(255) CHARACTER SET ascii NOT NULL, PRIMARY KEY(`id`, `owner`), FOREIGN KEY(`owner`) REFERENCES `owner`(`id`) ON DELETE CASCADE ); -- CREATE TABLE `event` ( -- `id` CHAR(36) CHARACTER SET ascii NOT NULL, -- `owner` CHAR(36) CHARACTER SET ascii NOT NULL, -- `updated` DATETIME(3) NOT NULL, -- `text` TEXT DEFAULT NULL, -- `scheduled` DATETIME DEFAULT NULL, -- `done` DATETIME DEFAULT NULL, -- `income` FLOAT NOT NULL DEFAULT 0, -- `expense` FLOAT NOT NULL DEFAULT 0, -- `source` CHAR(36) CHARACTER SET ascii DEFAULT NULL, -- PRIMARY KEY(`id`, `owner`), -- FOREIGN KEY(`id`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE, -- FOREIGN KEY(`source`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE -- ); -- CREATE TABLE `event_history` ( -- `id` CHAR(36) CHARACTER SET ascii NOT NULL, -- `owner` CHAR(36) CHARACTER SET ascii NOT NULL, -- `updated` DATETIME(3) NOT NULL, -- `action` VARCHAR(255) NOT NULL, -- `text` TEXT DEFAULT NULL, -- `scheduled` DATETIME DEFAULT NULL, -- `done` DATETIME DEFAULT NULL, -- `income` FLOAT DEFAULT NULL, -- `expense` FLOAT DEFAULT NULL, -- `source` CHAR(36) CHARACTER SET ascii DEFAULT NULL, -- PRIMARY KEY(`id`, `owner`, `updated`), -- FOREIGN KEY(`id`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE -- ); CREATE TABLE `note` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `owner` CHAR(36) CHARACTER SET ascii NOT NULL, `updated` DATETIME(3) NOT NULL, `title` VARCHAR(255) DEFAULT NULL, `text` TEXT DEFAULT NULL, PRIMARY KEY(`id`, `owner`), FOREIGN KEY(`id`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE ); CREATE TABLE `note_history` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `owner` CHAR(36) CHARACTER SET ascii NOT NULL, `updated` DATETIME(3) NOT NULL, `action` VARCHAR(255) NOT NULL, `title` VARCHAR(255) DEFAULT NULL, `text` TEXT DEFAULT NULL, PRIMARY KEY(`id`, `owner`, `updated`), FOREIGN KEY(`id`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE ); -- CREATE TABLE `board` ( -- `id` CHAR(36) CHARACTER SET ascii NOT NULL, -- `owner` CHAR(36) CHARACTER SET ascii NOT NULL, -- `updated` DATETIME(3) NOT NULL, -- `title` VARCHAR(255) DEFAULT NULL, -- `text` TEXT DEFAULT NULL, -- PRIMARY KEY(`id`, `owner`), -- FOREIGN KEY(`id`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE -- ); -- CREATE TABLE `board_history` ( -- `id` CHAR(36) CHARACTER SET ascii NOT NULL, -- `owner` CHAR(36) CHARACTER SET ascii NOT NULL, -- `updated` DATETIME(3) NOT NULL, -- `action` VARCHAR(255) NOT NULL, -- `title` VARCHAR(255) DEFAULT NULL, -- `text` TEXT DEFAULT NULL, -- PRIMARY KEY(`id`, `owner`, `updated`), -- FOREIGN KEY(`id`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE -- ); CREATE TABLE `category` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `owner` CHAR(36) CHARACTER SET ascii NOT NULL, `updated` DATETIME(3) NOT NULL, `title` VARCHAR(255) DEFAULT NULL, `text` TEXT DEFAULT NULL, `parent` CHAR(36) CHARACTER SET ascii DEFAULT NULL, PRIMARY KEY(`id`, `owner`), FOREIGN KEY(`id`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE, FOREIGN KEY(`parent`, `owner`) REFERENCES `category`(`id`, `owner`) ON DELETE CASCADE ); CREATE TABLE `category_history` ( `id` CHAR(36) CHARACTER SET ascii NOT NULL, `owner` CHAR(36) CHARACTER SET ascii NOT NULL, `updated` DATETIME(3) NOT NULL, `action` VARCHAR(255) NOT NULL, `title` VARCHAR(255) DEFAULT NULL, `text` TEXT DEFAULT NULL, `parent` CHAR(36) CHARACTER SET ascii DEFAULT NULL, PRIMARY KEY(`id`, `owner`, `updated`), FOREIGN KEY(`id`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE ); -- CREATE TABLE `boardnote` ( -- `owner` CHAR(36) CHARACTER SET ascii NOT NULL, -- `board` CHAR(36) CHARACTER SET ascii NOT NULL, -- `note` CHAR(36) CHARACTER SET ascii NOT NULL, -- `updated` DATETIME(3) NOT NULL, -- PRIMARY KEY(`owner`, `board`, `note`), -- FOREIGN KEY(`board`, `owner`) REFERENCES `board`(`id`, `owner`) ON DELETE CASCADE, -- FOREIGN KEY(`note`, `owner`) REFERENCES `note`(`id`, `owner`) ON DELETE CASCADE -- ); -- CREATE TABLE `boardnote_history` ( -- `owner` CHAR(36) CHARACTER SET ascii NOT NULL, -- `board` CHAR(36) CHARACTER SET ascii NOT NULL, -- `note` CHAR(36) CHARACTER SET ascii NOT NULL, -- `updated` DATETIME(3) NOT NULL, -- `action` VARCHAR(255) NOT NULL, -- PRIMARY KEY(`owner`, `board`, `note`, `updated`), -- FOREIGN KEY(`board`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE, -- FOREIGN KEY(`note`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE -- ); CREATE TABLE `categoryentity` ( `owner` CHAR(36) CHARACTER SET ascii NOT NULL, `category` CHAR(36) CHARACTER SET ascii NOT NULL, `entity` CHAR(36) CHARACTER SET ascii NOT NULL, `updated` DATETIME(3) NOT NULL, PRIMARY KEY(`owner`, `category`, `entity`), FOREIGN KEY(`category`, `owner`) REFERENCES `category`(`id`, `owner`) ON DELETE CASCADE, FOREIGN KEY(`entity`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE ); CREATE TABLE `categoryentity_history` ( `owner` CHAR(36) CHARACTER SET ascii NOT NULL, `category` CHAR(36) CHARACTER SET ascii NOT NULL, `entity` CHAR(36) CHARACTER SET ascii NOT NULL, `updated` DATETIME(3) NOT NULL, `action` VARCHAR(255) NOT NULL, PRIMARY KEY(`owner`, `category`, `entity`, `updated`), FOREIGN KEY(`category`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE, FOREIGN KEY(`entity`, `owner`) REFERENCES `entity`(`id`, `owner`) ON DELETE CASCADE ); CREATE TRIGGER `insert_user` BEFORE INSERT ON `user` FOR EACH ROW INSERT IGNORE INTO `owner` (`id`, `table`) VALUE(NEW.id, 'user'); -- CREATE TRIGGER `insert_event` BEFORE INSERT ON `event` -- FOR EACH ROW -- INSERT IGNORE INTO `entity` (`id`, `owner`, `table`) VALUE(NEW.id, NEW.owner, 'event'); CREATE TRIGGER `insert_note` BEFORE INSERT ON `note` FOR EACH ROW INSERT IGNORE INTO `entity` (`id`, `owner`, `table`) VALUE(NEW.id, NEW.owner, 'note'); -- CREATE TRIGGER `insert_board` BEFORE INSERT ON `board` -- FOR EACH ROW -- INSERT IGNORE INTO `entity` (`id`, `owner`, `table`) VALUE(NEW.id, NEW.owner, 'board'); CREATE TRIGGER `insert_category` BEFORE INSERT ON `category` FOR EACH ROW INSERT IGNORE INTO `entity` (`id`, `owner`, `table`) VALUE(NEW.id, NEW.owner, 'category'); CREATE TRIGGER `insert_user_history` AFTER INSERT ON `user` FOR EACH ROW INSERT INTO `user_history` (`action`, `id`, `updated`, `email`, `username`, `password`) VALUE('insert', NEW.id, NEW.updated, NEW.email, NEW.username, NEW.password); CREATE TRIGGER `update_user_history` AFTER UPDATE ON `user` FOR EACH ROW INSERT INTO `user_history` (`action`, `id`, `updated`, `email`, `username`, `password`) VALUE('update', NEW.id, NEW.updated, NEW.email, NEW.username, NEW.password); CREATE TRIGGER `delete_user_history` AFTER DELETE ON `user` FOR EACH ROW INSERT INTO `user_history` (`action`, `id`, `updated`, `email`, `username`, `password`) VALUE('delete', OLD.id, NOW(), OLD.email, OLD.username, OLD.password); -- CREATE TRIGGER `insert_event_history` AFTER INSERT ON `event` -- FOR EACH ROW -- INSERT INTO `event_history` (`action`, `id`, `owner`, `updated`, `text`, `scheduled`, `done`, `income`, `expense`, `source`) -- VALUE('insert', NEW.id, NEW.owner, NEW.updated, NEW.text, NEW.scheduled, NEW.done, NEW.income, NEW.expense, NEW.source); -- CREATE TRIGGER `update_event_history` AFTER UPDATE ON `event` -- FOR EACH ROW -- INSERT INTO `event_history` (`action`, `id`, `owner`, `updated`, `text`, `scheduled`, `done`, `income`, `expense`, `source`) -- VALUE('update', NEW.id, NEW.owner, NEW.updated, NEW.text, NEW.scheduled, NEW.done, NEW.income, NEW.expense, NEW.source); -- CREATE TRIGGER `delete_event_history` AFTER DELETE ON `event` -- FOR EACH ROW -- INSERT INTO `event_history` (`action`, `id`, `owner`, `updated`, `text`, `scheduled`, `done`, `income`, `expense`, `source`) -- VALUE('delete', OLD.id, OLD.owner, NOW(), OLD.text, OLD.scheduled, OLD.done, OLD.income, OLD.expense, OLD.source); CREATE TRIGGER `insert_note_history` AFTER INSERT ON `note` FOR EACH ROW INSERT INTO `note_history` (`action`, `id`, `owner`, `updated`, `text`, `title`) VALUE('insert', NEW.id, NEW.owner, NEW.updated, NEW.text, NEW.title); CREATE TRIGGER `update_note_history` AFTER UPDATE ON `note` FOR EACH ROW INSERT INTO `note_history` (`action`, `id`, `owner`, `updated`, `text`, `title`) VALUE('update', NEW.id, NEW.owner, NEW.updated, NEW.text, NEW.title); CREATE TRIGGER `delete_note_history` AFTER DELETE ON `note` FOR EACH ROW INSERT INTO `note_history` (`action`, `id`, `owner`, `updated`, `text`, `title`) VALUE('delete', OLD.id, OLD.owner, NOW(), OLD.text, OLD.title); -- CREATE TRIGGER `insert_board_history` AFTER INSERT ON `board` -- FOR EACH ROW -- INSERT INTO `board_history` (`action`, `id`, `owner`, `updated`, `title`, `text`) -- VALUE('insert', NEW.id, NEW.owner, NEW.updated, NEW.title, NEW.text); -- CREATE TRIGGER `update_board_history` AFTER UPDATE ON `board` -- FOR EACH ROW -- INSERT INTO `board_history` (`action`, `id`, `owner`, `updated`, `title`, `text`) -- VALUE('update', NEW.id, NEW.owner, NEW.updated, NEW.title, NEW.text); -- CREATE TRIGGER `delete_board_history` AFTER DELETE ON `board` -- FOR EACH ROW -- INSERT INTO `board_history` (`action`, `id`, `owner`, `updated`, `title`, `text`) -- VALUE('delete', OLD.id, OLD.owner, NOW(), OLD.title, OLD.text); CREATE TRIGGER `insert_category_history` AFTER INSERT ON `category` FOR EACH ROW INSERT INTO `category_history` (`action`, `id`, `owner`, `updated`, `title`, `text`, `parent`) VALUE('insert', NEW.id, NEW.owner, NEW.updated, NEW.title, NEW.text, NEW.parent); CREATE TRIGGER `update_category_history` AFTER UPDATE ON `category` FOR EACH ROW INSERT INTO `category_history` (`action`, `id`, `owner`, `updated`, `title`, `text`, `parent`) VALUE('update', NEW.id, NEW.owner, NEW.updated, NEW.title, NEW.text, NEW.parent); CREATE TRIGGER `delete_category_history` AFTER DELETE ON `category` FOR EACH ROW INSERT INTO `category_history` (`action`, `id`, `owner`, `updated`, `title`, `text`, `parent`) VALUE('delete', OLD.id, OLD.owner, NOW(), OLD.title, OLD.text, OLD.parent); -- CREATE TRIGGER `insert_boardnote_history` AFTER INSERT ON `boardnote` -- FOR EACH ROW -- INSERT INTO `boardnote_history` (`action`, `owner`, `board`, `note`, `updated`) -- VALUE('insert', NEW.owner, NEW.board, NEW.note, NEW.updated); -- CREATE TRIGGER `update_boardnote_history` AFTER UPDATE ON `boardnote` -- FOR EACH ROW -- INSERT INTO `boardnote_history` (`action`, `owner`, `board`, `note`, `updated`) -- VALUE('update', NEW.owner, NEW.board, NEW.note, NEW.updated); -- CREATE TRIGGER `delete_boardnote_history` AFTER DELETE ON `boardnote` -- FOR EACH ROW -- INSERT INTO `boardnote_history` (`action`, `owner`, `board`, `note`, `updated`) -- VALUE('delete', OLD.owner, OLD.board, OLD.note, NOW()); CREATE TRIGGER `insert_categoryentity_history` AFTER INSERT ON `categoryentity` FOR EACH ROW INSERT INTO `categoryentity_history` (`action`, `owner`, `category`, `entity`, `updated`) VALUE('insert', NEW.owner, NEW.category, NEW.entity, NEW.updated); CREATE TRIGGER `update_categoryentity_history` AFTER UPDATE ON `categoryentity` FOR EACH ROW INSERT INTO `categoryentity_history` (`action`, `owner`, `category`, `entity`, `updated`) VALUE('update', NEW.owner, NEW.category, NEW.entity, NEW.updated); CREATE TRIGGER `delete_categoryentity_history` AFTER DELETE ON `categoryentity` FOR EACH ROW INSERT INTO `categoryentity_history` (`action`, `owner`, `category`, `entity`, `updated`) VALUE('delete', OLD.owner, OLD.category, OLD.entity, NOW());
true
305ec6c9085024427dbd67cfabdc5f43888ef7fa
SQL
rhindli/utils
/scloud/sql/createUsers.sql
UTF-8
880
2.8125
3
[]
no_license
-- Create SocrateOpen User CREATE USER sopen IDENTIFIED BY sopen DEFAULT TABLESPACE USERS TEMPORARY TABLESPACE TEMP PROFILE DEFAULT ACCOUNT UNLOCK; GRANT CONNECT, DBA, RESOURCE TO sopen WITH ADMIN OPTION; GRANT INSERT ANY TABLE TO sopen WITH ADMIN OPTION; GRANT SELECT ANY TABLE TO sopen WITH ADMIN OPTION; GRANT EXECUTE ANY PROCEDURE TO sopen WITH ADMIN OPTION; GRANT DELETE ANY TABLE TO sopen WITH ADMIN OPTION; GRANT UPDATE ANY TABLE TO sopen WITH ADMIN OPTION; GRANT UNLIMITED TABLESPACE TO sopen; -- Create SDWH User CREATE USER sdwh IDENTIFIED BY sdwh DEFAULT TABLESPACE USERS TEMPORARY TABLESPACE TEMP PROFILE DEFAULT ACCOUNT UNLOCK; GRANT CONNECT, DBA, RESOURCE TO sdwh; GRANT INSERT ANY TABLE TO sdwh; GRANT SELECT ANY TABLE TO sdwh; GRANT EXECUTE ANY PROCEDURE TO sdwh; GRANT DELETE ANY TABLE TO sdwh; GRANT UPDATE ANY TABLE TO sdwh; GRANT UNLIMITED TABLESPACE TO sdwh;
true
0aff441c2e733de2bec4b7304335ce26187b2be7
SQL
JLucas220/ProjetoPW-S
/dadosPWS.sql
UTF-8
11,233
2.84375
3
[]
no_license
use projetopws; insert into aeroportos values (default, 'Aeroporto de Lisboa', 'Lisboa', 'Portugal', 'Alameda das Comunidades Portuguesas, 1700-111 Lisboa'), (default, 'Aeroporto Francisco Sa Carneiro', 'Porto', 'Portugal', '4470-558 Vila Nova da Telha'), (default, 'Aeroporto Internacional Domodedovo', 'Moscovo', 'Russia', 'Moscow Oblast, Rússia'), (default, 'Aeroporto de Helsinquia-Vantaa', 'Helsinquia ', 'Finlandia', '01531 Vantaa, Finlândia'), (default, 'Aeroporto de Hamburgo', 'Hamburgo', 'Alemanha', 'Flughafenstr. 1-3, 22335 Hamburg, Alemanha'), (default, 'Aeroporto de Copenhaga', 'Copenhaga', 'Dinamarca', 'Lufthavnsboulevarden 6, 2770 Kastrup, Dinamarca'), (default, 'Aeroporto de Paris-Charles de Gaulle', 'Paris', 'Franca', '95700 Roissy-en-France, Franca'), (default, 'Aeroporto de Madrid-Barajas', 'Madrid', 'Espanha', 'Av de la Hispanidad, s/n, 28042 Madrid, Espanha'), (default, 'Aeroporto de Budapeste Ferenc Liszt', 'Budapeste', 'Hungria', 'Budapest, 1185 Hungria'), (default, 'Aeroporto de Amesterdão Schiphol', 'Amesterdao', 'Paises Baixos', 'Evert van de Beekstraat 202, 1118 CP Schiphol, Paises Baixos'), (default, 'Aeroporto Internacional de Roma', 'Roma', 'Italia', "Via dell'Aeroporto di Fiumicino, 00054 Fiumicino RM, Italia"), (default, 'Aeroporto de Manchester', 'Manchester', 'Reino Unido', 'Manchester M90 1QX, Reino Unido'), (default, 'Aeroporto de Londres Heathrow', 'Londres', 'Reino Unido', 'Longford TW6, Reino Unido'); insert into users values (default, 'João', 'Lucas', '938472618', '[email protected]', 'Rua do Castelo, nr 13', 'lucas', '1234', 'administrador'), (default, 'Francisco', 'Matias', '987654321', '[email protected]', 'Rua do lameirao, nr 24', 'matias', '1234', 'administrador'), (default, 'Guilherme', 'Carolino', '918765412', '[email protected]', 'Rua do Arco, nr 2', 'gui', '1234', 'administrador'), (default, 'Marco', 'Marques', '912348298', '[email protected]', 'Rua da Luz, nr 69', 'marquez', '1234', 'gestor'), (default, 'Miguel', 'Pombo', '954334534' '[email protected]', 'Largo de Alvalade, nr 85', 'miguel', '1234', 'operador'), (default, 'Bruno', 'Honório', '918762484', '[email protected]', 'Rua da Marmelada, nr 90', 'bruno', '1234', 'passageiro'), (default, 'Paulo', 'Gonzo', '968435623', '[email protected]', 'Avenida dos Lagartos, nr 99', 'paulo', '1234', 'passageiro'), (default, 'Tiago', 'Horta', '923414146', '[email protected]', 'Rua de Magalhães, nr 43', 'tiago', '1234', 'passageiro'); insert into planes values (default, 'Boeing', '787-10', '336', 'p787001'), (default, 'Boeing', '737-9Max', '220', 'p737001'), (default, 'Embraer', 'E-195', '108', 'p195001'), (default, 'Airbus', 'a330-900neo', '330', 'p330001'); insert into voos values -- 1 escala (ida) (default, 1, 13, 1263, '4149', 325), -- lisboa - londres (default, 1, 7, 890, '3101', 374), -- lisboa - Paris (default, 1, 13, 810, '3487', 394), -- lisboa - londres -- 1 escala (volta) (default, 13, 1, 1263, '4149', 325), -- londres - lisboa (default, 7, 1, 890, '3101', 374), -- Paris - lisboa (default, 13, 1, 810, '3487', 394), -- londres - lisboa -- 2 escalas (ida) (default, 1, 9, 1263, '4149', 325), -- lisboa - budapeste (default, 1, 3, 890, '3101', 374), -- lisboa - moscovo (default, 1, 4, 810, '3487', 394), -- lisboa - helsinquia -- 2 escalas (volta) (default, 9, 1, 1263, '4149', 325), -- budapeste - lisboa (default, 3, 1, 890, '3101', 374), -- moscovo - lisboa (default, 4, 1, 810, '3487', 394), -- helsinquia - lisboa -- 3 escalas (ida) (default, 1, 3, 1263, '4149', 325), -- lisboa - moscovo (default, 1, 3, 890, '3101', 374), -- lisboa - moscovo (default, 1, 11, 810, '3487', 394), -- lisboa - Roma -- 3 escalas (volta) (default, 3, 1, 1263, '4149', 325), -- moscovo - lisboa (default, 3, 1, 890, '3101', 374), -- moscovo - lisboa (default, 11, 1, 810, '3487', 394); -- Roma - lisboa insert into escalas values (default, 1, 1, 2, '2021-06-18 14:20:00', '2021-06-18 15:10:00', 285, 50), -- lisboa - porto (default, 1, 2, 13, '2021-06-18 15:40:00', '2021-06-18 17:42:00', 1312, 122), -- porto - londres -- ........................................................................................... (default, 2, 1, 2, '2021-06-12 20:45:00', '2021-06-12 20:35:00', 285, 50), -- lisboa - porto (default, 2, 2, 7, '2021-06-12 20:55:00', '2021-06-12 22:50:00', 1206, 115), -- porto - paris -- ........................................................................................... (default, 3, 1, 7, '2021-06-10 09:05:00', '2021-06-10 11:10:00', 1445, 131), -- lisboa - paris (default, 3, 7, 13, '2021-06-10 12:40:00', '2021-06-10 13:35:00', 359, 55), -- paris - londres -- ........................................................................................... -- ........................................................................................... (default, 4, 13, 2, '2021-06-21 12:25:00', '2021-06-21 14:27:00', 1312, 122), -- londres - porto (default, 4, 2, 1, '2021-06-21 15:55:00', '2021-06-21 16:45:00', 285, 50), -- porto - lisboa -- ........................................................................................... (default, 5, 7, 2, '2021-06-15 18:45:00', '2021-06-15 19:51:00', '517', 66), -- paris - porto (default, 5, 2, 1, '2021-06-15 19:00:00', '2021-06-15 20:43:00', '1042', 103), -- porto - lisboa -- ........................................................................................... (default, 6, 13, 7, '2021-06-12 21:00:00', '2021-06-12 22:23:00', '752', 83), -- londres - paris (default, 6, 7, 1, '2021-06-12 22:45:00', '2021-06-12 23:34:00', '282', 49), -- paris - lisboa -- ........................................................................................... -- ........................................................................................... (default, 7, 1, 8, '2021-06-24 06:40:00', '2021-06-24 07:46:00', 517, 66), -- lisboa - madrid (default, 7, 8, 11, '2021-06-24 8:10:00', '2021-06-24 10:15:00', 1356, 125), -- madrid - roma (default, 7, 11, 9, '2021-06-24 10:50:00', '2021-06-24 12:17:00', 815, 87), -- roma - budapeste -- ........................................................................................... (default, 8, 1, 7, '2021-07-03 16:50:00', '2021-07-03 19:01:00', 1445, 131), -- lisboa - paris (default, 8, 7, 6, '2021-07-03 19:35:00', '2021-07-03 21:17:00', 1028, 102), -- paris - copenhaga (default, 8, 6, 3, '2021-07-03 21:40:00', '2021-07-04 00:00:00', 1562, 140), -- copenhaga - moscovo -- ........................................................................................... (default, 9, 1, 12, '2021-07-13 10:10:00', '2021-07-13 12:40:00', 1709, 170), -- lisboa - manchester (default, 9, 12, 5, '2021-07-13 13:15:00', '2021-07-13 14:42:00', 814, 87), -- manchester - hamburgo (default, 9, 5, 4, '2021-07-13 15:20:00', '2021-07-13 17:13:00', 1178, 113), -- hamburgo - helsinquia -- ........................................................................................... -- ........................................................................................... (default, 10, 9, 11, '2021-06-27 11:00:00', '2021-06-27 12:27:00', 815, 87), -- budapeste - roma (default, 10, 11, 8, '2021-06-27 12:50:00', '2021-06-27 14:55:00', 1356, 125), -- roma - madrid (default, 10, 8, 1, '2021-06-27 15:30:00', '2021-06-27 15:36:00', 517, 66), -- madrid - lisboa -- ........................................................................................... (default, 11, 3, 6, '2021-07-07 12:25:00', '2021-07-07 14:45:00', 1562, 140), -- moscovo - copenhaga (default, 11, 6, 7, '2021-07-07 15:35:00', '2021-07-07 17:07:00', 1028, 102), -- copenhaga - paris (default, 11, 7, 1, '2021-07-07 17:40:00', '2021-07-07 19:51:00', 1445, 131), -- paris - lisboa -- ........................................................................................... (default, 12, 4, 5, '2021-07-18 05:50:00', '2021-07-18 07:47:00', 1178, 113), -- helsinquia - hamburgo (default, 12, 5, 12, '2021-07-18 08:15:00', '2021-07-18 09:42:00', 814, 87), -- hamburgo - manchester (default, 12, 12, 1, '2021-07-18 10:20:00', '2021-07-18 13:10:00', 1709, 170), -- manchester - lisboa -- ...........................................................................................~ -- ........................................................................................... (default, 13, 1, 2, '2021-06-18 14:20:00', '2021-06-18 15:10:00', 285, 50), -- lisboa - porto (default, 13, 2, 13, '2021-06-18 15:40:00', '2021-06-18 17:42:00', 1312, 122), -- porto - londres (default, 13, 13, 4, '2021-06-18 18:20:00', '2021-06-18 20:59:00', 1836, 159), -- londres - helsinquia (default, 13, 4, 3, '2021-06-18 21:40:00', '2021-06-18 22:13:00', 902, 93), -- helsinquia - moscovo -- ........................................................................................... (default, 14, 1, 8, '2021-07-07 14:50:00', '2021-07-07 15:56:00', 517, 66), -- lisboa - madrid (default, 14, 8, 11, '2021-07-07 16:30:00', '2021-07-07 18:35:00', 1356, 125), -- madrid - roma (default, 14, 11, 9, '2021-07-07 19:10:00', '2021-07-07 20:37:00', 815, 87), -- roma - budapeste (default, 14, 9, 3, '2021-07-07 21:00:00', '2021-07-07 23:20:00', 1565, 140), -- budapeste - moscovo -- ........................................................................................... (default, 15, 1, 12, '2021-06-24 10:30:00', '2021-06-24 13:00:00', 1709, 150), -- lisboa - manchester (default, 15, 12, 7, '2021-06-24 13:20:00', '2021-06-24 14:32:00', 596, 72), -- manchester - paris (default, 15, 7, 5, '2021-06-24 15:00:00', '2021-06-24 16:23:00', 752, 83), -- paris - hamburgo (default, 15, 5, 11, '2021-06-24 17:00:00', '2021-06-24 19:03:00', 1319, 123), -- hamburgo - roma -- ........................................................................................... -- ........................................................................................... (default, 16, 3, 4, '2021-06-22 19:45:00', '2021-06-22 21:18:00', 902, 93), -- moscovo - helsinquia (default, 16, 4, 13, '2021-06-22 21:40:00', '2021-06-23 00:19:00', 1836, 159), -- helsinquia - londres (default, 16, 13, 2, '2021-06-23 00:50:00', '2021-06-23 02:52:00', 1312, 122), -- londres - porto (default, 16, 2, 1, '2021-06-23 03:15:00', '2021-06-23 04:05:00', 285, 50), -- porto - lisboa -- ........................................................................................... (default, 17, 3, 9, '2021-07-11 07:20:00', '2021-07-11 09:40:00', 1565, 140), -- moscovo - budapeste (default, 17, 9, 11, '2021-07-11 10:10:00', '2021-07-11 11:37:00', 815, 87), -- budapeste - roma (default, 17, 11, 8, '2021-07-11 12:05:00', '2021-07-11 14:10:00', 1356, 125), -- roma - madrid (default, 17, 8, 1, '2021-07-11 14:35:00', '2021-07-11 15:41:00', 517, 66), -- madrid - lisboa -- ........................................................................................... (default, 18, 11, 5, '2021-06-29 05:40:00', '2021-06-29 07:43:00', 1319, 123), -- roma - hamburgo (default, 18, 5, 7, '2021-06-29 08:05:00', '2021-06-29 09:28:00', 752, 83), -- hamburgo - paris (default, 18, 7, 12, '2021-06-29 10:00:00', '2021-06-29 11:12:00', 596, 72), -- paris - manchester (default, 18, 12, 1, '2021-06-29 11:40:00', '2021-06-29 14:10:00', 1709, 150); -- manchester - lisboa insert into escala_planes values (1,4), (2,4), (3,4), (4,4), (5,1), (6,1), (7,1), (8,1);
true
972fa72de9f344294178268da612379c34a185e8
SQL
silence-do-good/stress-test-Postgres-and-MySQL
/dump/high/day12/select1554.sql
UTF-8
191
2.78125
3
[]
no_license
SELECT timeStamp, temperature FROM ThermometerObservation WHERE timestamp>'2017-11-11T15:54:00Z' AND timestamp<'2017-11-12T15:54:00Z' AND SENSOR_ID='77429a10_2148_48c9_801f_ed7971bc0ae0'
true
3bc73d671c228549d7b6bae687aa2735dda6069d
SQL
ghillstr/Tech-Elevator-Final-Capstone--Big-Disk-Energy
/java/database/schema.sql
UTF-8
2,771
3.71875
4
[]
no_license
BEGIN TRANSACTION; DROP TABLE IF EXISTS scores; DROP TABLE IF EXISTS tee_time; DROP TABLE IF EXISTS invite; DROP TABLE IF EXISTS invite_status; DROP TABLE IF EXISTS users_leagues; DROP TABLE IF EXISTS leagues; DROP TABLE IF EXISTS users; DROP SEQUENCE IF EXISTS seq_user_id; CREATE SEQUENCE seq_user_id INCREMENT BY 1 NO MAXVALUE NO MINVALUE CACHE 1; CREATE TABLE users ( user_id int DEFAULT nextval('seq_user_id'::regclass) NOT NULL, username varchar(50) NOT NULL, password_hash varchar(200) NOT NULL, role varchar(50) NOT NULL, CONSTRAINT PK_user PRIMARY KEY (user_id) ); INSERT INTO users (username,password_hash,role) VALUES ('user','$2a$08$UkVvwpULis18S19S5pZFn.YHPZt3oaqHZnDwqbCW9pft6uFtkXKDC','ROLE_USER'); INSERT INTO users (username,password_hash,role) VALUES ('admin','$2a$08$UkVvwpULis18S19S5pZFn.YHPZt3oaqHZnDwqbCW9pft6uFtkXKDC','ROLE_ADMIN'); CREATE TABLE leagues ( league_id SERIAL PRIMARY KEY, username varchar(50) NOT NULL, course_name varchar(50) NOT NULL, league_name varchar(20) NOT NULL ); CREATE TABLE users_leagues ( league_id integer NOT NULL, user_id integer NOT NULL, CONSTRAINT fk_league_id FOREIGN KEY (league_id) REFERENCES leagues(league_id), CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users(user_id) ); CREATE TABLE invite_status ( status_id SERIAL PRIMARY KEY, status_type varchar(15) NOT NULL ); CREATE TABLE invite ( invite_id SERIAL PRIMARY KEY, status_id integer NOT NULL, league_id integer NOT NULL, league_name varchar(50) NOT NULL, user_id integer NOT NULL, username varchar(50) NOT NULL, CONSTRAINT fk_status_id FOREIGN KEY (status_id) REFERENCES invite_status(status_id), CONSTRAINT fk_league_id FOREIGN KEY (league_id) REFERENCES leagues(league_id), CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users(user_id) ); CREATE TABLE tee_time ( tee_time_id SERIAL PRIMARY KEY, user_id integer NOT NULL, username varchar(50) NOT NULL, league_id integer NOT NULL, league_name varchar(50) NOT NULL, tee_date date NOT NULL, start_time time NOT NULL, CONSTRAINT fk_league_id FOREIGN KEY (league_id) REFERENCES leagues(league_id), CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users(user_id) ); CREATE TABLE scores ( round_id SERIAL PRIMARY KEY, username varchar(50) NOT NULL, score_total integer, league_name varchar(50) NOT NULL ); COMMIT TRANSACTION; INSERT INTO invite_status (status_id, status_type) VALUES (DEFAULT, 'Pending'), (DEFAULT, 'Accepted'), (DEFAULT, 'Rejected'); <<<<<<< HEAD ======= >>>>>>> 99c8c3c8cd2186c8be9a522a6649173a36fde91c
true
69d9228497538149b61cbba776039e61bbfc1400
SQL
redareda9/shopify-app-express
/reports/order_stats_sums.sql
UTF-8
291
3.90625
4
[]
no_license
select to_char(po.created_date, 'YYYY-MM Month'), count(distinct order_id) as orders from product_orders po join shop_resources sr on sr.id = po.shop_resource_id join shops sh on sh.id = sr.shop_id and sh.created_date > '2021-06-17' group by 1 order by 1 desc;
true
40e2994d1924970f90992789844a706829b37aaa
SQL
flaviohnm/projetophp
/app/scritp/app_crud.sql
UTF-8
1,393
3.28125
3
[]
no_license
CREATE DATABASE app_crud; CREATE TABLE IF NOT EXISTS `app_crud`.`customers` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `cpf_cnpj` VARCHAR(14) NOT NULL, `birthdate` DATE NOT NULL, `address` VARCHAR(255) NOT NULL, `hood` VARCHAR(100) NOT NULL, `zip_code` VARCHAR(8) NOT NULL, `city` VARCHAR(100) NOT NULL, `state` VARCHAR(100) NOT NULL, `phone` VARCHAR(11) NOT NULL, `mobile` VARCHAR(11) NOT NULL, `ie` VARCHAR(11) NOT NULL, `created` DATETIME NOT NULL, `modified` DATETIME NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `id_UNIQUE` (`id` ASC) VISIBLE) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci INSERT INTO `customers` (`id`,`name`, `cpf_cnpj`, `birthdate`, `address`, `hood`, `zip_code`, `city`, `state`, `phone`, `mobile`, `ie`, `created`, `modified`) VALUES ('','Fulano de Tal', '123.456.789-00', '1989-01-01', 'Rua da Web, 123', 'Internet', '1234568', 'Teste', 'Teste', '5555555', '55555555', '123456', '2016-05-24 00:00:00', '2016-05-24 00:00:00'); INSERT INTO `customers` (`id`,`name`, `cpf_cnpj`, `birthdate`, `address`, `hood`, `zip_code`, `city`, `state`, `phone`, `mobile`, `ie`, `created`, `modified`) VALUES ('','Fulano de Tal', '123.456.789-00', '1989-01-01', 'Rua da Web, 123', 'Internet', '1234568', 'Teste', 'Teste', '5555555', '55555555', '123456', '2016-05-24 00:00:00', '2016-05-24 00:00:00');
true
9a9194463b71a2f6de52316a7b32233318f58487
SQL
msolyakov/net-mvc-sample-app
/trunk/v1/Flat4Me.Database/cmn/Stored Procedures/Auth/sp_Auth_UserClaim_GetList.sql
UTF-8
171
2.609375
3
[]
no_license
CREATE PROCEDURE [cmn].[sp_Auth_UserClaim_GetList] @UserId int AS BEGIN select [Type], [Value] from cmn.Auth_UserClaim with(nolock) where UserId = @UserId END
true
60adf0ba37be54476a65c7d5cc3c8ac5fc4bb9dc
SQL
CUBRID/cubrid-testcases
/sql/_29_CTE_recursive/_06_cte_join_normal/cases/01_example.sql
UTF-8
14,382
4.0625
4
[ "BSD-3-Clause" ]
permissive
drop table if exists t1,t2; create table t1 (a int, b varchar(32)); insert into t1 values (4,'aaaa' ), (7,'bb'), (1,'ccc'), (4,'dd'); insert into t1 values (3,'eee'), (7,'bb'), (1,'fff'), (4,'ggg'); create table t2 (c int); insert into t2 values (2), (4), (5), (3); with recursive t as (select a from t1 where b >= 'c') select * from t2,t where t2.c=t.a order by 1,2; with recursive t as (select a from t1 where b >= 'c') select t2.*,t.* from t2,t where t2.c=t.a order by 1,2; select t2.*,t.* from t2, (select a from t1 where b >= 'c') as t where t2.c=t.a order by 1,2; with recursive t as (select * from t1 where b >= 'c') select * from t2,t where t2.c=t.a order by 1,2,3; with recursive t as (select * from t1 where b >= 'c') select t2.*,t.* from t2,t where t2.c=t.a order by 1,2,3; with recursive t(f1,f2) as (select * from t1 where b >= 'c') select * from t2,t where t2.c=t.f1 order by 1,2,3; with recursive t as (select a, count(*) from t1 where b >= 'c' group by a) select * from t2,t where t2.c=t.a order by 1,2,3; select * from t2, (select a, count(*) from t1 where b >= 'c' group by a) as t where t2.c=t.a order by 1,2,3; with recursive t as (select a, count(*) from t1 where b >= 'c' group by a having count(*)=1 ) select * from t2,t where t2.c=t.a order by 1,2,3; select * from t2, (select a, count(*) from t1 where b >= 'c' group by a having count(*)=1) t where t2.c=t.a order by 1,2,3; with recursive t as (select a, count(*) from t1 where b >= 'c' group by a having count(*)=1 ) select * from t2,t order by 1,2,3; select * from t2, (select a, count(*) from t1 where b >= 'c' group by a having count(*)=1) t order by 1,2,3; with recursive t as (select * from t2 where c <= 4) select a, count(*) from t1,t where t1.a=t.c group by a having count(*)=1; select a, count(*) from t1, (select * from t2 where c <= 4) t where t1.a=t.c group by a having count(*)=1; with recursive t as (select * from t2 where c <= 4 ) select a, count(*) from t1,t where t1.a=t.c group by a order by count(*); select a, count(*) from t1, (select * from t2 where c <= 4 ) t where t1.a=t.c group by a order by count(*); with recursive t as (select * from t2 where c <= 4 ) select a, count(*) from t1,t where t1.a=t.c group by a order by count(*) desc limit 1; select a, count(*) from t1, (select * from t2 where c <= 4 ) t where t1.a=t.c group by a order by count(*) desc limit 1; with recursive t as (select a from t1 where a<5) select * from t2 where c in (select a from t) order by 1; select * from t2 where c in (select a from (select a from t1 where a<5) as t) order by 1; with recursive t as (select count(*) as c from t1 where b >= 'c' group by a) select * from t2 where c in (select c from t) order by 1; select * from t2 where c in (select c from (select count(*) as c from t1 where b >= 'c' group by a) as t) order by 1; with recursive t as (select a from t1 where b >= 'c') select * from t as r1, t as r2 where r1.a=r2.a order by 1,2; select * from (select a from t1 where b >= 'c') as r1, (select a from t1 where b >= 'c') as r2 where r1.a=r2.a order by 1,2; with recursive t as (select distinct a from t1 where b >= 'c') select * from t as r1, t as r2 where r1.a=r2.a order by 1, 2; select * from (select distinct a from t1 where b >= 'c') as r1, (select distinct a from t1 where b >= 'c') as r2 where r1.a=r2.a order by 1,2 ; with recursive t as (select * from t1 where b >= 'c') select * from t as r1, t as r2 where r1.a=r2.a order by 1,2,3,4; select * from (select * from t1 where b >= 'c') as r1, (select * from t1 where b >= 'c') as r2 where r1.a=r2.a order by 1,2,3,4; with recursive t(c) as (select a from t1 where b >= 'c') select * from t r1, t r2 where r1.c=r2.c order by 1; with recursive t as (select a from t1 where b >= 'c') select * from t where a < 2 union select * from t where a >= 4 order by 1; select * from (select a from t1 where b >= 'c') as t where t.a < 2 union select * from (select a from t1 where b >= 'c') as t where t.a >= 4 order by 1; with recursive t as (select a from t1 where b >= 'f' union select c as a from t2 where c < 4) select * from t2,t where t2.c=t.a order by 1; select * from t2, (select a from t1 where b >= 'f' union select c as a from t2 where c < 4) as t where t2.c=t.a order by 1; --t is defined in the with recursive clause of a subquery --CBRD-20820 select t1.a,t1.b from t1,t2 where t1.a>t2.c and t2.c in (with recursive t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a) order by 1,2; select t1.a,t1.b from t1,t2 where t1.a>t2.c and t2.c in (select t2.c from t2,(select * from t1 where t1.a<5) as t where t2.c=t.a) order by 1,2; with recursive t as (select c from t2 where c >= 4) select t1.a,t1.b from t1,t where t1.a=t.c and t.c in (with recursive t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a) order by 1,2; select t1.a,t1.b from t1, (select c from t2 where c >= 4) as t where t1.a=t.c and t.c in (select t2.c from t2, (select * from t1 where t1.a<5) as t where t2.c=t.a) order by 1,2; with recursive t as (select * from t1 where a>2 and b in (with recursive tt as (select * from t2 where t2.c<5) select t1.b from t1,tt where t1.a=tt.c)) select t.a, count(*) from t1,t where t1.a=t.a group by t.a order by 1; select t.a, count(*) from t1, (select * from t1 where a>2 and b in (select t1.b from t1, (select * from t2 where t2.c<5) as tt where t1.a=tt.c)) as t where t1.a=t.a group by t.a order by 1; select * from t1, (with recursive t as (select a from t1 where b >= 'c') select * from t2,t where t2.c=t.a) as tt where t1.b > 'f' and tt.a=t1.a order by 1,2,3,4; select * from t1, (select * from t2, (select a from t1 where b >= 'c') as t where t2.c=t.a) as tt where t1.b > 'f' and tt.a=t1.a order by 1,2,3,4; create view v1 as with recursive t as (select a from t1 where b >= 'c') select * from t2,t where t2.c=t.a; show create view v1; select * from v1; create view v2 as with recursive t as (select a, count(*) from t1 where b >= 'c' group by a) select * from t2,t where t2.c=t.a; show create view v2; select * from v2; create view v3 as with recursive t(c) as (select a from t1 where b >= 'c') select * from t r1 where r1.c=4; show create view v3; select * from v3; create view v4(c,d) as with recursive t(c) as (select a from t1 where b >= 'c') select * from t r1, t r2 where r1.c=r2.c and r2.c=4; show create view v4; select * from v4; drop view v1,v2,v3,v4; create view v1(a) as with recursive t as (select a from t1 where b >= 'c') select t.a from t2,t where t2.c=t.a; update v1 set a=0 where a > 4; drop view v1; prepare stmt1 from ' with recursive t as (select a from t1 where b >= ?) select * from t2,t where t2.c=t.a order by 1'; execute stmt1 using 'c'; deallocate prepare stmt1; prepare stmt1 from ' with recursive t as (select a, count(*) from t1 where b >= ? group by a) select * from t2,t where t2.c=t.a order by 1,2,3'; execute stmt1 using 'c'; deallocate prepare stmt1; prepare stmt1 from ' with recursive t as (select * from t1 where b >= ?) select * from t as r1, t as r2 where r1.a=r2.a order by 1,2,3,4'; execute stmt1 using 'c'; deallocate prepare stmt1; --error with recursive t(f) as (select * from t1 where b >= 'c') select * from t2,t where t2.c=t.f1 order by 1; with recursive t(f1,f1) as (select * from t1 where b >= 'c') select * from t2,t where t2.c=t.f1 order by 1; with recursive t as (select * from t2 where c>3), t as (select a from t1 where a>2) select * from t,t1 where t1.a=t.c order by 1; with recursive t as (select a from s where a<5), s as (select a from t1 where b>='d') select * from t,s where t.a=s.a order by 1; with recursive recursive t as (select a from s where a<5), s as (select a from t1 where b>='d') select * from t,s where t.a=s.a order by 1; with recursive recursive t as (select * from s where a>2), s as (select a from t1,r where t1.a>r.c), r as (select c from t,t2 where t.a=t2.c) select * from r where r.c<7 order by 1; with recursive recursive t as (select * from s where a>2), s as (select a from t1,r where t1.a>r.c), r as (select c from t,t2 where t.a=t2.c) select * from r where r.c<7 order by 1; with recursive recursive t as (select * from t1 where a in (select c from s where b<='ccc') and b>'b'), s as (select * from t1,t2 where t1.a=t2.c and t1.c in (select a from t where a<5)) select * from s where s.b>'aaa' order by 1; with recursive t as (select count(*) from t1 where d>='f' group by a) select t1.b from t2,t1 where t1.a = t2.c order by 1; with recursive t(d) as (select count(*) from t1 where b<='ccc' group by b), s as (select * from t1 where a in (select t2.d from t2,t where t2.c=t.d)) select t1.b from t1,t2 where t1.a=t2.c order by 1; with recursive t(d) as (select count(*) from t1 where b<='ccc' group by b), s as (select * from t1 where a in (select t2.c from t2,t where t2.c=t.c)) select t1.b from t1,t2 where t1.a=t2.c order by 1; with recursive t(d) as (select count(*) from t1 where b<='ccc' group by b), s as (select * from t1 where a in (select t2.c from t2,t where t2.c=t.d)) select t1.b from t1,t2 where t1.a=t2.c order by 1; with recursive t(f) as (select * from t1 where b >= 'c') select t1.b from t2,t1 where t1.a = t2.c order by 1; with recursive t(f1,f1) as (select * from t1 where b >= 'c') select t1.b from t2,t1 where t1.a = t2.c order by 1; with recursive t as (select a, count(*) from t1 where b >= 'c' group by a) select t1.b from t2,t1 where t1.a = t2.c order by 1; with recursive t as (select c from t2 where c >= 4) select t1.a,t1.b from t1,t where t1.a=t.c and t.c in (with recursive t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a) order by 1,2; select t1.a,t1.b from t1,t2 where t1.a>t2.c and t2.c in (with recursive t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a) order by 1,2; with recursive t as (select * from t1 where a>2 and b in ( with recursive tt as ( select * from t2 where t2.c<5 ) select t1.b from t1,tt where t1.a=tt.c) ) select t.a, count(*) from t1,t where t1.a=t.a group by t.a order by 1,2; drop table if exists t1,t2,t3; create table t1 (a int, b varchar(32)); insert into t1 values (4,'aaaa' ), (7,'bb'), (1,'ccc'), (4,'dd'); insert into t1 values (3,'eee'), (7,'bb'), (1,'fff'), (4,'ggg'); create table t2 (c int); insert into t2 values (2), (4), (5), (3); create table t3(i int); insert into t3 (with recursive t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a); select * from t3 order by 1; with recursive t as (select c from t2 where c >= 4) select t1.a,t1.b from t1,t where t1.a=t.c and t.c in (with recursive t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a) order by 1,2; with recursive t as (select c from t2 where c >= 4) select t1.a,t1.b from t1,t where t1.a=t.c and t.c in (select * from t3) order by 1,2; with recursive t as (select c from t2 where c >= 4) select t1.a,t1.b from t1,t where t1.a=t.c and t.c in (4,4,4,3) order by 1,2; with recursive t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a order by 1; drop table if exists t1,t2,t3; create table t1 (a int, b char(32)); insert into t1 values(4,'aaaa' ); insert into t1 values (7,'bb'); insert into t1 values (1,'ccc'); insert into t1 values (4,'dd'); insert into t1 values(3,'eee'); insert into t1 values (7,'bb'); insert into t1 values (1,'fff'); insert into t1 values(4,'ggg'); create table t2 (c int); insert into t2 values(2); insert into t2 values(4); insert into t2 values(5); insert into t2 values(3); with t as (select c from t2 where c >= 4) select t1.a,t1.b from t1,t where t1.a=t.c and t.c in (with t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a) order by 1,2; drop table if exists t1,t2,t3; create table t1 (a int, b char(32)); insert into t1 values(4,'aaaa' ); insert into t1 values (7,'bb'); insert into t1 values (1,'ccc'); insert into t1 values (4,'dd'); insert into t1 values(3,'eee'); insert into t1 values (7,'bb'); insert into t1 values (1,'fff'); insert into t1 values(4,'ggg'); create table t2 (c int); insert into t2 values(2); insert into t2 values(4); insert into t2 values(5); insert into t2 values(3); create table t3(i int); insert into t3 (with recursive t as ( select * from t1 where t1.a<5 ) select t2.c from t2,t where t2.c=t.a); select * from t3 order by 1; with t as (select c from t2 where c >= 4) select t1.a,t1.b from t1,t where t1.a=t.c and t.c in (with t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a) order by 1,2; drop table if exists t1,t2,t3; create table t1 (a int, b char(32)); insert into t1 values(4,'aaaa' ); insert into t1 values (7,'bb'); insert into t1 values (1,'ccc'); insert into t1 values (4,'dd'); insert into t1 values(3,'eee'); insert into t1 values (7,'bb'); insert into t1 values (1,'fff'); insert into t1 values(4,'ggg'); create table t2 (c int); insert into t2 values(2); insert into t2 values(4); insert into t2 values(5); insert into t2 values(3); with t as (select c from t2 where c >= 4) select t1.a,t1.b from t1,t where t1.a=t.c and t.c in (with t as (select * from t1 where t1.a<5) select t2.c from t2,t where t2.c=t.a) order by 1,2; drop if exists t1,t2,t3;
true
8b6ce4ce69948c142b7b4a877d3f590d030aac3c
SQL
jengfad/webscraping
/others/cp-magicians/schema.sql
UTF-8
596
2.984375
3
[]
no_license
USE CP; CREATE TABLE IF NOT EXISTS error_logs ( id INT AUTO_INCREMENT PRIMARY KEY, notes TEXT, error_message TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS magicians ( id INT AUTO_INCREMENT PRIMARY KEY, name TEXT, email TEXT, location TEXT, index_letter_url TEXT, website TEXT, location_url TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS finished_locations ( id INT AUTO_INCREMENT PRIMARY KEY, location TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
true
014f86547606d3d23a8672b66897aa4eb8e706fc
SQL
Andrey1de/andrey1de-rates
/sql/Stocks.CreateTable.sql
UTF-8
439
2.8125
3
[]
no_license
SET TRANSACTION READ WRITE; CREATE TABLE Stocks ( symbol varchar(8) CONSTRAINT firstkey PRIMARY KEY, region varchar(8) NULL, shortname varchar(20) NULL, quoteType varchar(10) NOT NULL, index varchar(10) NOT NULL, score double NOT NULL, typeDisp varchar(80) NOT NULL, longname varchar(20) NULL, percent double NOT NULL, updated date );
true
130c2c425cdacfe1863ae4f7d9695abf3d699c7b
SQL
dickeawacs/awacs
/code/ecp/src/main/resources/DBscript/ATS备份数据库过程(执行1).sql
UTF-8
18,731
2.5625
3
[]
no_license
DELIMITER $$ USE `ats`$$ DROP PROCEDURE IF EXISTS `buildData`$$ CREATE PROCEDURE `buildData`( ) BEGIN DECLARE onenum INT DEFAULT 1; DECLARE onemax INT DEFAULT 128; DECLARE twonum INT DEFAULT 0; DECLARE twomax INT DEFAULT 255; DECLARE userIndex INT DEFAULT 0; -- 一层设备循环 WHILE onenum<=onemax DO SET twonum=0; -- 二层设备循环 WHILE twonum<=twomax DO INSERT INTO `table_10_bak` ( /**`field1`,*//***序号 ***/ `field2`,/*** [废弃] ***/ `field3`,/*** 一层设备网络地址 ***/ `field4`,/*** 二层设备网络地址 ***/ `field5`,/*** 设备启用状态位 ***/ `field6`,/*** 输入交叉状态位 ***/ `field7`,/*** 联动输出状态位 ***/ `field8`,/*** 设备唯一ID ***/ `field9`,/*** 设备生产序列号 ***/ `field10`,/*** 设备种类 ***/ `field11`,/*** 设备通讯正/异常 ***/ `field12`,/*** 电压检测 ***/ `field13`,/*** 设备被撬 ***/ `field14`,/*** 输入状态 ***/ `field15`,/*** 输出状态 ***/ `field16`,/*** 用户防区布撤防状态 ***/ /****1.屏蔽输入。 1.0x00 2.普通输入。 2.0x01 3.立即防区。 3.0x02 4.24小时防区。4.0x03 */ `field17`,/*** 1输入(防区)属性 ***/ `field18`,/*** 2输入(防区)属性 ***/ `field19`,/*** 3输入(防区)属性 ***/ `field20`,/*** 4输入(防区)属性 ***/ `field21`,/*** 5输入(防区)属性 ***/ `field22`,/*** 6输入(防区)属性 ***/ `field23`,/*** 7输入(防区)属性 ***/ `field24`,/*** 8输入(防区)属性 ***/ `field25`,/*** 1输入(防区)隶属属性 ***/ `field26`,/*** 2输入(防区)隶属属性 ***/ `field27`,/*** 3输入(防区)隶属属性 ***/ `field28`,/*** 4输入(防区)隶属属性 ***/ `field29`,/*** 5输入(防区)隶属属性 ***/ `field30`,/*** 6输入(防区)隶属属性 ***/ `field31`,/*** 7输入(防区)隶属属性 ***/ `field32`,/*** 8输入(防区)隶属属性 ***/ `field33`,/*** 输入1输入交叉信息 ***/ `field34`,/*** 输入2输入交叉信息 ***/ `field35`,/*** 输入3输入交叉信息 ***/ `field36`,/*** 输入4输入交叉信息 ***/ `field37`,/*** 输入5输入交叉信息 ***/ `field38`,/*** 输入6输入交叉信息 ***/ `field39`,/*** 输入7输入交叉信息 ***/ `field40`,/*** 输入8输入交叉信息 ***/ /****输入1联动///***/ `field41`,/*** 输入1联动输出信息1 ***/ `field42`,/*** 输入1联动输出信息2 ***/ `field43`,/*** 输入1联动输出信息3 ***/ `field44`,/*** 输入1联动输出信息4 ***/ `field45`,/*** 输入1联动输出信息5 ***/ `field46`,/*** 输入1联动输出信息6 ***/ `field47`,/*** 输入1联动输出信息7 ***/ `field48`,/*** 输入1联动输出信息8 ***/ /**输入2联动/////////////**/ `field49`,/*** 输入2联动输出信息1 ***/ `field50`,/*** 输入2联动输出信息2 ***/ `field51`,/*** 输入2联动输出信息3 ***/ `field52`,/*** 输入2联动输出信息4 ***/ `field53`,/*** 输入2联动输出信息5 ***/ `field54`,/*** 输入2联动输出信息6 ***/ `field55`,/*** 输入2联动输出信息7 ***/ `field56`,/*** 输入2联动输出信息8 ***/ /*输入3联动//////****/ `field57`,/*** 输入3联动输出信息1 ***/ `field58`,/*** 输入3联动输出信息2 ***/ `field59`,/*** 输入3联动输出信息3 ***/ `field60`,/*** 输入3联动输出信息4 ***/ `field61`,/*** 输入3联动输出信息5 ***/ `field62`,/*** 输入3联动输出信息6 ***/ `field63`,/*** 输入3联动输出信息7 ***/ `field64`,/*** 输入3联动输出信息8 ***/ /*输入4联动*/ `field65`,/*** 输入4联动输出信息1 ***/ `field66`,/*** 输入4联动输出信息2 ***/ `field67`,/*** 输入4联动输出信息3 ***/ `field68`,/*** 输入4联动输出信息4 ***/ `field69`,/*** 输入4联动输出信息5 ***/ `field70`,/*** 输入4联动输出信息6 ***/ `field71`,/*** 输入4联动输出信息7 ***/ `field72`,/*** 输入4联动输出信息8 ***/ /*输入5联动*/ `field73`,/*** 输入5联动输出信息1 ***/ `field74`,/*** 输入5联动输出信息2 ***/ `field75`,/*** 输入5联动输出信息3 ***/ `field76`,/*** 输入5联动输出信息4 ***/ `field77`,/*** 输入5联动输出信息5 ***/ `field78`,/*** 输入5联动输出信息6 ***/ `field79`,/*** 输入5联动输出信息7 ***/ `field80`,/*** 输入5联动输出信息8 ***/ /*输入6联动*/ `field81`,/*** 输入6联动输出信息1 ***/ `field82`,/*** 输入6联动输出信息2 ***/ `field83`,/*** 输入6联动输出信息3 ***/ `field84`,/*** 输入6联动输出信息4 ***/ `field85`,/*** 输入6联动输出信息5 ***/ `field86`,/*** 输入6联动输出信息6 ***/ `field87`,/*** 输入6联动输出信息7 ***/ `field88`,/*** 输入6联动输出信息8 ***/ /*输入7联动*/ `field89`,/*** 输入7联动输出信息1 ***/ `field90`,/*** 输入7联动输出信息2 ***/ `field91`,/*** 输入7联动输出信息3 ***/ `field92`,/*** 输入7联动输出信息4 ***/ `field93`,/*** 输入7联动输出信息5 ***/ `field94`,/*** 输入7联动输出信息6 ***/ `field95`,/*** 输入7联动输出信息7 ***/ `field96`,/*** 输入7联动输出信息8 ***/ /*输入8联动*/ `field97`,/*** 输入8联动输出信息1 ***/ `field98`,/*** 输入8联动输出信息2 ***/ `field99`,/*** 输入8联动输出信息3 ***/ `field100`,/*** 输入8联动输出信息4 ***/ `field101`,/*** 输入8联动输出信息5 ***/ `field102`,/*** 输入8联动输出信息6 ***/ `field103`,/*** 输入8联动输出信息7 ***/ `field104`,/*** 输入8联动输出信息8 ***/ `field105`,/*** 输入1名称 ***/ `field106`,/*** 输入2名称 ***/ `field107`,/*** 输入3名称 ***/ `field108`,/*** 输入4名称 ***/ `field109`,/*** 输入5名称 ***/ `field110`,/*** 输入6名称 ***/ `field111`,/*** 输入7名称 ***/ `field112`,/*** 输入8名称 ***/ `field113`,/*** 输出1名称 ***/ `field114`,/*** 输出2名称 ***/ `field115`,/*** 输出3名称 ***/ `field116`,/*** 输出4名称 ***/ `field117`,/*** 输出5名称 ***/ `field118`,/*** 输出6名称 ***/ `field119`,/*** 输出7名称 ***/ `field120`,/*** 输出8名称 ***/ `field121`,/*** 二层设备名称 ***/ `field122`,/**输入1触发提示音**/ `field123`,/**输入2触发提示音**/ `field124`,/**输入3触发提示音**/ `field125`,/**输入4触发提示音**/ `field126`,/**输入5触发提示音**/ `field127`,/**输入6触发提示音**/ `field128`,/**输入7触发提示音**/ `field129`,/**输入8触发提示音**/ `field130`,/**屏蔽状态(1为屏蔽禁用)**/ `field131`,/**输入1恢复提示音*/ `field132`,/**输入2恢复提示音*/ `field133`,/**输入3恢复提示音*/ `field134`,/**输入4恢复提示音*/ `field135`,/**输入5恢复提示音*/ `field136`,/**输入6恢复提示音*/ `field137`,/**输入7恢复提示音*/ `field138`,/**输入8恢复提示音*/ `field139`,/**输出1闭合提示音**/ `field140`,/**输出2闭合提示音**/ `field141`,/**输出3闭合提示音**/ `field142`,/**输出4闭合提示音**/ `field143`,/**输出5闭合提示音**/ `field144`,/**输出6闭合提示音**/ `field145`,/**输出7闭合提示音**/ `field146`,/**输出8闭合提示音**/ `field147`,/**输出1断开提示音**/ `field148`,/**输出2断开提示音**/ `field149`,/**输出3断开提示音**/ `field150`,/**输出4断开提示音**/ `field151`,/**输出5断开提示音**/ `field152`,/**输出6断开提示音**/ `field153`,/**输出7断开提示音**/ `field154`,/**输出8断开提示音**/ `field155`,/*输出1状态**/ `field156`,/*输出2状态**/ `field157`,/*输出3状态**/ `field158`,/*输出4状态**/ `field159`,/*输出5状态**/ `field160`,/*输出6状态**/ `field161`,/*输出7状态**/ `field162`,/*输出8状态**/ `oneType`,/**一层设备类型**/ `fip`,/**设备的IP地址**/ `fport`,/**设备的访问端口 **/ `disabletel`,/**禁用电话端口 禁用为1,启用为0,默认为0**/ `disablemessage`,/**禁用短信端口 禁用为1,启用为0,默认为0**/ `telnum1`,/**接警中心号码一**/ `telnum2`,/**接警中心号码2**/ `telspace`,/**电话通迅间隔(分钟):**/ `messagespace`,/**短信通迅间隔(分钟):**/ `printset`,/**打印设置(禁止时为“”,不禁止时为"报警事件,普通输入事件,用户操作事件",其中0表示未选中,1表示选中**/ `dtype`/**设置类型(1:一层设备,2:二层设备)**/ ) VALUES ( /**`field1`,*//***序号 ***/ NULL ,/*** [废弃] ***/ onenum,/*** 一层设备网络地址 ***/ twonum,/*** 二层设备网络地址 ***/ 0,/*** 设备启用状态位 ***/ 0,/*** 输入交叉状态位 ***/ 0,/*** 联动输出状态位 ***/ '0',/*** 设备唯一ID ***/ '0',/*** 设备生产序列号 ***/ 0,/*** 设备种类 ***/ 0,/*** 设备通讯正/异常 ***/ 0,/*** 电压检测 ***/ 0,/*** 设备被撬 ***/ 0,/*** 输入状态 ***/ 0,/*** 输出状态 ***/ 0,/*** 用户防区布撤防状态 ***/ /****1.屏蔽输入。 1.0x00 2.普通输入。 2.0x01 3.立即防区。 3.0x02 4.24小时防区。4.0x03 */ IF(TWONUM=0,1,1),/*** 1输入(防区)属性 ***/ IF(TWONUM=0,2,1),/*** 2输入(防区)属性 ***/ IF(TWONUM=0,3,1),/*** 3输入(防区)属性 ***/ IF(TWONUM=0,4,1),/*** 4输入(防区)属性 ***/ IF(TWONUM=0,5,1),/*** 5输入(防区)属性 ***/ IF(TWONUM=0,6,1),/*** 6输入(防区)属性 ***/ IF(TWONUM=0,7,1),/*** 7输入(防区)属性 ***/ IF(TWONUM=0,8,1),/*** 8输入(防区)属性 ***/ 0,/*** 1输入(防区)隶属属性 ***/ 0,/*** 2输入(防区)隶属属性 ***/ 0,/*** 3输入(防区)隶属属性 ***/ 0,/*** 4输入(防区)隶属属性 ***/ 0,/*** 5输入(防区)隶属属性 ***/ 0,/*** 6输入(防区)隶属属性 ***/ 0,/*** 7输入(防区)隶属属性 ***/ 0,/*** 8输入(防区)隶属属性 ***/ /**输入选择(输入1-8)--,交叉信息1字节,交叉信息2字节,交叉信息3字节输入选择**/ '0,0,0',/*** 输入1输入交叉信息 ***/ '0,0,0',/*** 输入2输入交叉信息 ***/ '0,0,0',/*** 输入3输入交叉信息 ***/ '0,0,0',/*** 输入4输入交叉信息 ***/ '0,0,0',/*** 输入5输入交叉信息 ***/ '0,0,0',/*** 输入6输入交叉信息 ***/ '0,0,0',/*** 输入7输入交叉信息 ***/ '0,0,0',/*** 输入8输入交叉信息 ***/ /***输入选择(输入1-8,默认1),输出联动输出(1-8)--,联动输出的1层地址,联动输出的2层地址,联动的输出端口号,联动属性,**/ '0,0,0,0,1',/*** 输入1联动输出信息1 ***/ '0,0,0,0,1',/*** 输入1联动输出信息2 ***/ '0,0,0,0,1',/*** 输入1联动输出信息3 ***/ '0,0,0,0,1',/*** 输入1联动输出信息4 ***/ '0,0,0,0,1',/*** 输入1联动输出信息5 ***/ '0,0,0,0,1',/*** 输入1联动输出信息6 ***/ '0,0,0,0,1',/*** 输入1联动输出信息7 ***/ '0,0,0,0,1',/*** 输入1联动输出信息8 ***/ /**输入2联动/////////////**/ '0,0,0,0,1',/*** 输入2联动输出信息1 ***/ '0,0,0,0,1',/*** 输入2联动输出信息2 ***/ '0,0,0,0,1',/*** 输入2联动输出信息3 ***/ '0,0,0,0,1',/*** 输入2联动输出信息4 ***/ '0,0,0,0,1',/*** 输入2联动输出信息5 ***/ '0,0,0,0,1',/*** 输入2联动输出信息6 ***/ '0,0,0,0,1',/*** 输入2联动输出信息7 ***/ '0,0,0,0,1',/*** 输入2联动输出信息8 ***/ /*输入3联动//////****/ '0,0,0,0,1',/*** 输入3联动输出信息1 ***/ '0,0,0,0,1',/*** 输入3联动输出信息2 ***/ '0,0,0,0,1',/*** 输入3联动输出信息3 ***/ '0,0,0,0,1',/*** 输入3联动输出信息4 ***/ '0,0,0,0,1',/*** 输入3联动输出信息5 ***/ '0,0,0,0,1',/*** 输入3联动输出信息6 ***/ '0,0,0,0,1',/*** 输入3联动输出信息7 ***/ '0,0,0,0,1',/*** 输入3联动输出信息8 ***/ /*输入4联动*/ '0,0,0,0,1',/*** 输入4联动输出信息1 ***/ '0,0,0,0,1',/*** 输入4联动输出信息2 ***/ '0,0,0,0,1',/*** 输入4联动输出信息3 ***/ '0,0,0,0,1',/*** 输入4联动输出信息4 ***/ '0,0,0,0,1',/*** 输入4联动输出信息5 ***/ '0,0,0,0,1',/*** 输入4联动输出信息6 ***/ '0,0,0,0,1',/*** 输入4联动输出信息7 ***/ '0,0,0,0,1',/*** 输入4联动输出信息8 ***/ /*输入5联动*/ '0,0,0,0,1',/*** 输入5联动输出信息1 ***/ '0,0,0,0,1',/*** 输入5联动输出信息2 ***/ '0,0,0,0,1',/*** 输入5联动输出信息3 ***/ '0,0,0,0,1',/*** 输入5联动输出信息4 ***/ '0,0,0,0,1',/*** 输入5联动输出信息5 ***/ '0,0,0,0,1',/*** 输入5联动输出信息6 ***/ '0,0,0,0,1',/*** 输入5联动输出信息7 ***/ '0,0,0,0,1',/*** 输入5联动输出信息8 ***/ /*输入6联动*/ '0,0,0,0,1',/*** 输入6联动输出信息1 ***/ '0,0,0,0,1',/*** 输入6联动输出信息2 ***/ '0,0,0,0,1',/*** 输入6联动输出信息3 ***/ '0,0,0,0,1',/*** 输入6联动输出信息4 ***/ '0,0,0,0,1',/*** 输入6联动输出信息5 ***/ '0,0,0,0,1',/*** 输入6联动输出信息6 ***/ '0,0,0,0,1',/*** 输入6联动输出信息7 ***/ '0,0,0,0,1',/*** 输入6联动输出信息8 ***/ /*输入7联动*/ '0,0,0,0,1',/*** 输入7联动输出信息1 ***/ '0,0,0,0,1',/*** 输入7联动输出信息2 ***/ '0,0,0,0,1',/*** 输入7联动输出信息3 ***/ '0,0,0,0,1',/*** 输入7联动输出信息4 ***/ '0,0,0,0,1',/*** 输入7联动输出信息5 ***/ '0,0,0,0,1',/*** 输入7联动输出信息6 ***/ '0,0,0,0,1',/*** 输入7联动输出信息7 ***/ '0,0,0,0,1',/*** 输入7联动输出信息8 ***/ /*输入8联动*/ '0,0,0,0,1',/*** 输入8联动输出信息1 ***/ '0,0,0,0,1',/*** 输入8联动输出信息2 ***/ '0,0,0,0,1',/*** 输入8联动输出信息3 ***/ '0,0,0,0,1',/*** 输入8联动输出信息4 ***/ '0,0,0,0,1',/*** 输入8联动输出信息5 ***/ '0,0,0,0,1',/*** 输入8联动输出信息6 ***/ '0,0,0,0,1',/*** 输入8联动输出信息7 ***/ '0,0,0,0,1',/*** 输入8联动输出信息8 ***/ CONCAT('设备',LPAD(twonum,3,'0'),1,'输入'),/*** 输入1名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),2,'输入'),/*** 输入2名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),3,'输入'),/*** 输入3名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),4,'输入'),/*** 输入4名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),5,'输入'),/*** 输入5名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),6,'输入'),/*** 输入6名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),7,'输入'),/*** 输入7名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),8,'输入'),/*** 输入8名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),1,'输出'),/*** 输出1名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),2,'输出'),/*** 输出2名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),3,'输出'),/*** 输出3名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),4,'输出'),/*** 输出4名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),5,'输出'),/*** 输出5名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),6,'输出'),/*** 输出6名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),7,'输出'),/*** 输出7名称 ***/ CONCAT('设备',LPAD(twonum,3,'0'),8,'输出'),/*** 输出8名称 ***/ ( CASE WHEN twonum=0 THEN CONCAT( '一层设备',LPAD(onenum,3,'0')) ELSE CONCAT( '二层设备',LPAD(twonum,3,'0')) END ),/*** 二层设备名称 ***/ 1,/**输入1触发提示音**/ 1,/**输入2触发提示音**/ 1,/**输入3触发提示音**/ 1,/**输入4触发提示音**/ 1,/**输入5触发提示音**/ 1,/**输入6触发提示音**/ 1,/**输入7触发提示音**/ 1,/**输入8触发提示音**/ 0,/**屏蔽状态(1为屏蔽禁用)**/ 2,/**输入1恢复提示音*/ 2,/**输入2恢复提示音*/ 2,/**输入3恢复提示音*/ 2,/**输入4恢复提示音*/ 2,/**输入5恢复提示音*/ 2,/**输入6恢复提示音*/ 2,/**输入7恢复提示音*/ 2,/**输入8恢复提示音*/ 3,/**输出1闭合提示音**/ 3,/**输出2闭合提示音**/ 3,/**输出3闭合提示音**/ 3,/**输出4闭合提示音**/ 3,/**输出5闭合提示音**/ 3,/**输出6闭合提示音**/ 3,/**输出7闭合提示音**/ 3,/**输出8闭合提示音**/ 4,/**输出1断开提示音**/ 4,/**输出2断开提示音**/ 4,/**输出3断开提示音**/ 4,/**输出4断开提示音**/ 4,/**输出5断开提示音**/ 4,/**输出6断开提示音**/ 4,/**输出7断开提示音**/ 4,/**输出8断开提示音**/ 0,/*输出1状态**/ 0,/*输出2状态**/ 0,/*输出3状态**/ 0,/*输出4状态**/ 0,/*输出5状态**/ 0,/*输出6状态**/ 0,/*输出7状态**/ 0,/*输出8状态**/ 0,/**一层设备类型**/ NULL,/**设备的IP地址**/ NULL,/**设备的访问端口 **/ '0',/**禁用电话端口 禁用为1,启用为0,默认为0**/ '0',/**禁用短信端口 禁用为1,启用为0,默认为0**/ '',/**接警中心号码一**/ '',/**接警中心号码2**/ 0,/**电话通迅间隔(分钟):**/ 0,/**短信通迅间隔(分钟):**/ '1,1,1,1',/**打印设置(禁止时为“”,不禁止时为"报警事件,普通输入事件,用户操作事件",其中0表示未选中,1表示选中**/ IF(TWONUM=0,1,2)/**设置类型(1:一层设备,2:二层设备)**/ ) ; IF TWONUM=0 THEN SET userIndex=0; WHILE userIndex<=16 DO INSERT INTO `ats`.`table_1_bak` ( `field2`, `field3`, `field4`, `field5`, `field6`, `field7`, `field8`, `field9`, `field10`, `field11`, `field12`, `field13`, `field14`, `field100`) VALUES ( -- 冗余的名字 IF(userIndex=0,CONCAT(LPAD(onenum,4,'0'),'管理员'),CONCAT(LPAD(onenum,4,'0'),'用户',LPAD(userIndex,2,'0'))), -- 用户名 IF(userIndex=0,CONCAT(LPAD(onenum,4,'0'),'管理员'),CONCAT(LPAD(onenum,4,'0'),'用户',LPAD(userIndex,2,'0'))), -- 密码 IF(userIndex=0,'12345678','123456'), -- 用户类型 2设备管理员,3用户 IF(userIndex=0,2,3), 0, '', 0, '', 0, onenum, userIndex, 0, 0, ''); SET userIndex=userIndex+1; END WHILE ; END IF ; -- 2层设备编号加1 SET twonum=twonum+1; END WHILE; -- 1层设备编号加1 SET onenum=onenum+1; END WHILE; COMMIT ; END$$ DELIMITER ;
true
b320acdb571cf98c167b56f80413a76c58656989
SQL
victorjmacmed/SQL-for-data-science--IBM-course
/SQL code/Project1_create_table_testcode/SQL_script1-2.sql
UTF-8
1,128
4.0625
4
[]
no_license
/* This is a practice scrip using SQL */ /* This code builds a table with some variables, then we insert some data, later we select all the columns. Then we select some particular columns, later on we update the city of instructor 1. To conclude we delete a particular row*/ DROP table INSTRUCTOR; CREATE table INSTRUCTOR ( ins_id INTEGER PRIMARY KEY NOT NULL, lastname VARCHAR(15), firstname VARCHAR(15), city VARCHAR(15), country CHAR(2) ); INSERT INTO INSTRUCTOR VALUES ( 1, 'Ahuja', 'Raj', 'Toronto', 'CA'); INSERT INTO INSTRUCTOR VALUES ( 2, 'Chong', 'Raul', 'Toronto', 'CA'), ( 3, 'Vasudevan', 'Hima', 'Chicago', 'US'); SELECT * FROM INSTRUCTOR; SELECT FIRSTNAME, CITY, COUNTRY FROM INSTRUCTOR WHERE CITY = 'Toronto'; /* The syntaxis distinguish capital letters. For instance, if we write 'TORONTO' the last line of code does not work*/ UPDATE INSTRUCTOR SET CITY = 'Markham' WHERE INS_ID = 1; DELETE FROM INSTRUCTOR WHERE INS_ID = 2; SELECT * FROM INSTRUCTOR;
true
d403652c8dfd838958c912a6d5e8e41c28e9e998
SQL
oxoxoline/database
/lesson8/homework.sql
UTF-8
3,114
4.34375
4
[]
no_license
-- 1. Добавить необходимые внешние ключи для всех таблиц базы данных vk (приложить команды). ALTER TABLE profiles ADD CONSTRAINT profiles_user_id_fk FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, ADD CONSTRAINT profiles_photo_id_fk FOREIGN KEY (photo_id) REFERENCES media(id) ON DELETE SET NULL; ALTER TABLE messages ADD CONSTRAINT messages_from_user_id_fk FOREIGN KEY (from_user_id) REFERENCES users(id), ADD CONSTRAINT messages_to_user_id_fk FOREIGN KEY (to_user_id) REFERENCES users(id), ADD CONSTRAINT messages_to_community_id_fk FOREIGN KEY (to_community_id) REFERENCES communities(id); ALTER TABLE posts ADD CONSTRAINT posts_user_id_fk FOREIGN KEY (user_id) REFERENCES users(id), ADD CONSTRAINT posts_media_id_fk FOREIGN KEY (media_id) REFERENCES media(id); ALTER TABLE media ADD CONSTRAINT media_user_id_fk FOREIGN KEY (user_id) REFERENCES users(id), ADD CONSTRAINT media_media_type_id_fk FOREIGN KEY (media_type_id) REFERENCES media_types(id); ALTER TABLE likes ADD CONSTRAINT likes_user_id_fk FOREIGN KEY (user_id) REFERENCES users(id), ADD CONSTRAINT likes_target_type_id_fk FOREIGN KEY (target_type_id) REFERENCES target_types(id), ADD CONSTRAINT likes_target_id_fk FOREIGN KEY (target_id) REFERENCES users(id); ALTER TABLE friendship ADD CONSTRAINT friendship_user_id_fk FOREIGN KEY (user_id) REFERENCES users(id), ADD CONSTRAINT friendship_friend_id_fk FOREIGN KEY (friend_id) REFERENCES users(id), ADD CONSTRAINT friendship_status_id_fk FOREIGN KEY (status_id) REFERENCES friendship_statuses(id); ALTER TABLE orders ADD CONSTRAINT orders_user_id_fk FOREIGN KEY (user_id) REFERENCES users(id); ALTER TABLE communities_users ADD CONSTRAINT communities_users_user_id_fk FOREIGN KEY (user_id) REFERENCES users(id); ALTER TABLE communities_users ADD CONSTRAINT communities_users_community_id_fk FOREIGN KEY (community_id) REFERENCES communities(id); -- 3. Переписать запросы, заданые к ДЗ урока 6 с использованием JOIN (три запроса). -- Не выполнил. Не до конца разобрался с обычным объединением, с JOIN ещё трудней стало. -- Поситать общее кол-во лайков, которые получили 10 самых молодых поользователей. SELECT SUM(got_likes) AS total_likes_for_youngest FROM ( SELECT COUNT(DISTINCT likes.id) AS got_likes FROM profiles LEFT JOIN likes ON likes.target_id = profiles.user_id AND target_type_id = 2 GROUP BY profiles.user_id ORDER BY profiles.birthday DESC LIMIT 10 ) AS youngest; -- Определить кто больше поставил лайков мужчины или женщины? SELECT profiles.sex AS SEX, COUNT(likes.id) AS total_likes FROM likes JOIN profiles ON likes.user_id = profiles.user_id GROUP BY profiles.sex ORDER BY total_likes DESC LIMIT 1;
true
34502910195b197d40506b6b0ccea9d355169e36
SQL
fishstudy/codeigniter_advance
/wz_yixun_proj/document/开发设计/资料类文档/website.sql
UTF-8
3,284
3.28125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.3.8 -- http://www.phpmyadmin.net -- -- Host: 10.24.179.138:3306 -- Generation Time: 2015-03-30 15:38:39 -- 服务器版本: 5.5.40 -- PHP Version: 5.3.14 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: `weidian` -- -- -------------------------------------------------------- -- -- 表的结构 `website` -- DROP TABLE IF EXISTS `website`; CREATE TABLE IF NOT EXISTS `website` ( `id` int(11) unsigned NOT NULL, `webMasterId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '对应站长的id', `bgPicture` varchar(256) NOT NULL DEFAULT '' COMMENT '背景图片', `articleList` varchar(64) NOT NULL DEFAULT '' COMMENT '文章列表标题', `productList` varchar(64) NOT NULL DEFAULT '' COMMENT '商品列表标题', `actList` varchar(64) NOT NULL DEFAULT '' COMMENT '活动列表标题', `createTime` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间', `createUser` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '创建人,采用易迅id', `updateTime` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '最后更新时间', `updateUser` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '最后更新人,采用易迅id', `conditions` tinyint(4) unsigned NOT NULL DEFAULT '1' COMMENT '有效1-16,无效17-32,备用33-', `articleModel` tinyint(4) unsigned NOT NULL DEFAULT '1' COMMENT '文章列表模板', `productModel` tinyint(4) unsigned NOT NULL DEFAULT '1' COMMENT '商品列表模板', `actModel` tinyint(4) unsigned NOT NULL DEFAULT '1' COMMENT '活动展示列表', `advModel` tinyint(4) unsigned NOT NULL DEFAULT '1' COMMENT '广告模板' ) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8 COMMENT='微站属性表'; -- -- Indexes for dumped tables -- -- -- Indexes for table `website` -- ALTER TABLE `website` ADD PRIMARY KEY (`id`), ADD KEY `webMasterId` (`webMasterId`), ADD KEY `conditions` (`conditions`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `website` -- ALTER TABLE `website` MODIFY `id` int(11) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10000; /*!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 */; /*新微站 - 一期 添加的字段 20150818*/ ALTER TABLE `website` ADD `recommend` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '达人推荐理由' ; ALTER TABLE `website` ADD `actLogo` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '热销活动基本设置-logo' ; ALTER TABLE `website` ADD `actPic` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '热销活动基本设置-背景图' ; ALTER TABLE `website` ADD `actTitle` VARCHAR(256) NULL COMMENT '热销活动基本设置-标题' ; ALTER TABLE `website` ADD `actCoupon` TINYINT(2) UNSIGNED NOT NULL DEFAULT '2' COMMENT '热销活动-是否在首页展示优惠券1是2否(默认)' ;
true
3e085b77fe31003d337150fd154a8f726570391d
SQL
antkudruk/test-for-carbonclick
/src/main/resources/db/migration/V1__Create_Participant.sql
UTF-8
223
2.515625
3
[]
no_license
create table participant ( participant_id bigint not null primary key auto_increment, first_name varchar(64) not null , last_name varchar(64) not null, email varchar(128) not null, unique(first_name, last_name) );
true
c46799475178e801104f0c1020fb4ea4f684c0e1
SQL
Guilherme-Marcionilo/MySQL-and-SpringBoot
/Modulo II - Banco de dados/table_funcionario.sql
UTF-8
527
3.453125
3
[]
no_license
create database RH; use RH; drop table funcionarios; CREATE table funcionarios( id int primary key auto_increment, nome varchar(30), sexo enum('M','F'), salario decimal(10,3), peso decimal(5,2) ); insert into funcionarios (nome,sexo,salario,peso) values ('Guilherme','M','1.000','50.2'), ('Junior','M','12.000','60.2'); select * from funcionarios; select * from funcionarios where salario > 2.000; select * from funcionarios where salario < 2.000; update funcionarios set nome = 'Novo Nome', sexo = 'F' where id = '1';
true
251a3d6b1581ad3bbc8bfcaa45f7c3b985ccf5b7
SQL
carolynmary/employee-management-system
/db/schema.sql
UTF-8
836
3.921875
4
[ "MIT" ]
permissive
DROP DATABASE IF EXISTS employee_management_db; CREATE DATABASE employee_management_db; USE employee_management_db; CREATE TABLE departments ( dept_id INT NOT NULL AUTO_INCREMENT, department VARCHAR(30) NOT NULL, PRIMARY KEY (dept_id) ); CREATE TABLE roles ( role_id INT NOT NULL AUTO_INCREMENT, title VARCHAR(30) NOT NULL, salary DECIMAL(10, 2) NOT NULL, dept_id INT NOT NULL, PRIMARY KEY (role_id), FOREIGN KEY (dept_id) REFERENCES departments(dept_id) ); CREATE TABLE employees ( employee_id INT NOT NULL AUTO_INCREMENT, first_name VARCHAR(30) NOT NULL, last_name VARCHAR(30) NOT NULL, role_id INT NOT NULL, manager_id INT, PRIMARY KEY (employee_id), FOREIGN KEY (role_id) REFERENCES roles(role_id), FOREIGN KEY (manager_id) REFERENCES employees(employee_id) );
true
8c5095da50fbe79b278da069111b7100a8da6d37
SQL
baked-pan/Code-PHP-Dev
/PHParticle/045/Resource/045_5.sql
UTF-8
5,307
2.671875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 2016-12-27 09:20:23 -- 服务器版本: 5.7.11 -- PHP Version: 7.1.0 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 latin1 */; -- -- Database: `phpdemo` -- -- -------------------------------------------------------- -- -- 表的结构 `045_5` -- CREATE TABLE `045_5` ( `teacher_id` varchar(50) NOT NULL, `teacher_name` char(20) DEFAULT NULL, `teacher_sex` char(10) DEFAULT NULL, `teacher_bir` varchar(50) DEFAULT NULL, `teacher_dept` varchar(50) DEFAULT NULL, `teacher_zc` varchar(50) DEFAULT NULL, `teacher_tel` char(30) DEFAULT NULL, `teacher_pwd` varchar(50) DEFAULT '2016123' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- 转存表中的数据 `045_5` -- INSERT INTO `045_5` (`teacher_id`, `teacher_name`, `teacher_sex`, `teacher_bir`, `teacher_dept`, `teacher_zc`, `teacher_tel`, `teacher_pwd`) VALUES ('20161001', '许成刚', '男', '1976-11-08', '信息技术学院', '副院长', '', '123456'), ('20161002', '赵营颖', '女', NULL, '信息技术学院', '讲师', NULL, '123456'), ('20161003', '王晨曦', '女', NULL, '人文学院', '讲师', NULL, '123456'), ('20161004', '韩一凡', '男', NULL, '思想政治理论教研部', '讲师', NULL, '123456'), (' 20161005', '韩倩倩', '女', NULL, '基础医学院', '讲师', NULL, '123456'), ('20161006', '王哲', '女', NULL, '信息技术学院', '主任', NULL, '123456'), ('20161007', '肖俊生', '男', NULL, '信息技术学院', '讲师', NULL, '123456'), ('2009090576', '耿方方', '女 ', NULL, '网络信息中心 ', '讲师 ', NULL, '123456'), ('2009091352', '曹莉', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2009090578', '陈昌爱', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2003070562', '高志宇', '男', '\n', '信息技术学院', '主任', '\n', '123456'), ('2004070566', '姜姗', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2006070550', '孔沈燕', '女', '\n', '信息技术学院', '书记', '\n', '123456'), ('2013121368', '李晓康', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2010080582', '廖璠', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2014010587', '刘俊娟', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2006070572', '吕雅丽', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2014011379', '吕志远', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2015051459', '牛秋月', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2007080573', '任靖娟', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2007070574', '宋学坤', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2006080569', '唐国良', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2004070565', '王昂', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2012050585', '王林景', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2010050580', '王晓鹏', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2010080581', '谢志豪', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2004070554', '徐燕文', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2009090575', '许玉龙', '男', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2010091353', '闫培玲', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2010080583', '赵春霞', '女', '\n', '信息技术学院', '讲师', '\n', '123456'), ('2007070547', '段涛', '男', '\n', '教育研究与教学评价中心', '讲师', '\n', '123456'), ('2010091351', '黄静', '女', '\n', '外语学院', '讲师', '\n', '123456'), ('2004070564', '李庆磊', '男', '', '教务处 ', '讲师', '', '123456'), ('2010080332', '李晓冰', '男', '\n', '基础医学院', '讲师', '\n', '123456'), ('2004070713', '李博', '男', '', '图书馆', ' 讲师', '', '123456'), ('2006070571', '柳忠勇', '男', '', '教务处 ', '讲师', '', '123456'), ('2013051340', '史占江', '男', '\n', '基础医学院', '讲师', '\n', '123456'), ('2015051497', '王超', '男', '\n', '人文学院', '讲师', '\n', '123456'), ('2009090577', '王忠义', '男', '\n', '网络信息中心', '讲师', '\n', '123456'), ('2006050615', '张太行', '男', '', '教务处 ', '讲师', '', '123456'), ('2009091117 ', '谭备战', '男', NULL, '思想政治理论教研部', '讲师', NULL, '2016123'), ('1998070404', '崔红新', '男', NULL, ' 人文学院', '讲师', NULL, '2016123'), ('2005090189 ', '李晓婧', '女', NULL, ' 外语学院', '讲师', NULL, '2016123'); -- -- Indexes for dumped tables -- -- -- Indexes for table `045_5` -- ALTER TABLE `045_5` ADD PRIMARY KEY (`teacher_id`); /*!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
6c42a8df2013781ee521c180d9dd32ba5aea0e7d
SQL
Ricardocanul7/Hotel
/SqlScript/db_hotel_DML.sql
UTF-8
1,278
2.578125
3
[]
no_license
use db_hotel; /* Estado de habitacion */ INSERT INTO estado_habitacion (estado) VALUES ('No disponible'); INSERT INTO estado_habitacion (estado) VALUES ('Mantenimiento'); INSERT INTO estado_habitacion (estado) VALUES ('Limpieza'); INSERT INTO estado_habitacion (estado) VALUES ('Disponible'); /* Puesto de empleado */ INSERT INTO puesto_empleado (puesto) VALUES ('Recepcion'); INSERT INTO puesto_empleado (puesto) VALUES ('Limpieza'); /* Tipo de transaccion */ INSERT INTO tipo_transaccion (nombre_transaccion) VALUES ('Efectivo'); INSERT INTO tipo_transaccion (nombre_transaccion) VALUES ('Tarjeta'); /* Tipo de usuario */ INSERT INTO tipo_usuario (nombre) VALUES ('Admin'); INSERT INTO tipo_usuario (nombre) VALUES ('Recepcionista'); INSERT INTO tipo_usuario (nombre) VALUES ('Propietario'); /* Tipo de habitaciones */ INSERT INTO tipo_habitacion (nombre_tipo) VALUES ('Sencilla'); INSERT INTO tipo_habitacion (nombre_tipo) VALUES ('Doble'); /* Estado de reservas INSERT INTO estado_reserva (estado_nombre) VALUE ('No pagado'); INSERT INTO estado_reserva (estado_nombre) VALUE ('Pagado'); */ INSERT INTO usuario (usuario_tipo, nombre, apellido_patern, apellido_matern, email, password) VALUES ('1', 'demo', 'demo', 'demo', 'demo', 'demo');
true
aa834a2988a9bf7fb9fcb29c64be6617c34844ab
SQL
kpapadopoul/dvd-rental-scripts
/6.sql
UTF-8
300
3.890625
4
[]
no_license
WITH film_rentals AS ( SELECT inventory.film_id, COUNT(*) FROM rental JOIN inventory ON rental.inventory_id = inventory.inventory_id GROUP BY inventory.film_id) SELECT film.*, film_rentals.count FROM film JOIN film_rentals ON film.film_id = film_rentals.film_id ORDER BY film_rentals.count DESC
true