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
ccbeab063fb39c0ca3e91f5d1e11dfb8096eae6a
SQL
salescube/SalesCube
/WEB/SalesCube/src/main/java/jp/co/arkinfosys/entity/sql/menu/FindAllMenuValidFlagForUser.sql
UTF-8
2,128
4.09375
4
[]
no_license
SELECT M.MENU_ID ,M.CAPTION ,M.DESCRIPTION ,M.URL ,M.PARENT_ID ,M.SEQ ,M.VALID_TYPE ,M.FONT_COLOR ,M.BG_COLOR ,M.CRE_FUNC ,M.CRE_DATETM ,M.CRE_USER ,M.UPD_FUNC ,M.UPD_DATETM ,M.UPD_USER ,'0' AS VALID_FLAG FROM MENU_MST_/*$domainId*/ M WHERE NOT EXISTS ( SELECT 1 FROM MENU_MST_/*$domainId*/ M2 LEFT OUTER JOIN ROLE_CFG_/*$domainId*/ RC ON M2.MENU_ID = RC.MENU_ID LEFT OUTER JOIN GRANT_ROLE_/*$domainId*/ GR ON RC.ROLE_ID = GR.ROLE_ID WHERE GR.USER_ID = /*userId*/'' AND RC.VALID_FLAG != '0' AND M2.MENU_ID = M.MENU_ID ) AND ( M.PARENT_ID IS NOT NULL OR M.MENU_ID IN ('1407','1500') ) UNION ALL SELECT M.MENU_ID ,M.CAPTION ,M.DESCRIPTION ,M.URL ,M.PARENT_ID ,M.SEQ ,M.VALID_TYPE ,M.FONT_COLOR ,M.BG_COLOR ,M.CRE_FUNC ,M.CRE_DATETM ,M.CRE_USER ,M.UPD_FUNC ,M.UPD_DATETM ,M.UPD_USER ,MAX(RC.VALID_FLAG) AS VALID_FLAG FROM MENU_MST_/*$domainId*/ M LEFT OUTER JOIN ROLE_CFG_/*$domainId*/ RC ON M.MENU_ID = RC.MENU_ID LEFT OUTER JOIN GRANT_ROLE_/*$domainId*/ GR ON RC.ROLE_ID = GR.ROLE_ID WHERE GR.USER_ID = /*userId*/'' AND RC.VALID_FLAG != '0' GROUP BY M.MENU_ID ,M.CAPTION ,M.DESCRIPTION ,M.URL ,M.PARENT_ID ,M.SEQ ,M.VALID_TYPE ,M.FONT_COLOR ,M.BG_COLOR ,M.CRE_FUNC ,M.CRE_DATETM ,M.CRE_USER ,M.UPD_FUNC ,M.UPD_DATETM ,M.UPD_USER ORDER BY MENU_ID
true
682f662dd190e79d6e8335ca2eb14ed1893300fb
SQL
pl3nny/sql_pl3nny
/section_7/advanced_query_using_correlated_subqueries.sql
UTF-8
1,417
4.75
5
[]
no_license
SELECT first_name, salary FROM employees WHERE salary > (SELECT round(AVG(salary)) FROM employees) -- avg sub query will run for every record in the initial query -- query below gets the average salary for each department SELECT first_name, salary FROM employees e1 WHERE salary > (SELECT round(AVG(salary)) FROM employees e2 WHERE e1.department = e2.department) -- another example by setting a column as a corolated subquery SELECT first_name, department, salary, ( SELECT round(AVG(salary)) FROM employees e2 WHERE e1.department = e2.department ) AS avg_department_salary FROM employees e1 -- write a query that contains more than 30 employees per department SELECT e1.first_name, e1.department FROM employees e1 WHERE e1.department IN ( SELECT e2.department FROM employees e2 GROUP BY e2.department HAVING COUNT(e2.employee_id) > 38 ) ORDER BY department -- better solotion below as it only involves searching each department no not each employee SELECT department FROM departments d WHERE 38 < ( SELECT COUNT(*) FROM employees e WHERE d.department = e.department ) -- Add another column with the highest paid employee from the departments in the previous -- query SELECT department, ( SELECT MAX(salary) FROM employees e WHERE e.department = d.department ) FROM departments d WHERE 38 < ( SELECT COUNT(*) FROM employees e WHERE d.department = e.department )
true
2dde7ef32e8ae7e2da8565a48f3676f6539e4344
SQL
dj199209/Study_Notedaily
/NoteDaily/117_28_mysql_day28/7_01_teacher_mysql_day28/SQL语句文件/查询排序.sql
UTF-8
499
3.21875
3
[]
no_license
/* 查询,对结果集进行排序 升序,降序,对指定列排序 order by 列名 [desc][asc] desc 降序 asc 升序排列,可以不写 */ -- 查询账务表,价格进行升序 SELECT * FROM zhangwu ORDER BY zmoney ASC -- 查询账务表,价格进行降序 SELECT * FROM zhangwu ORDER BY zmoney DESC -- 查询账务表,查询所有的支出,对金额降序排列 -- 先过滤条件 where 查询的结果再排序 SELECT * FROM zhangwu WHERE zname LIKE'%支出%' ORDER BY zmoney DESC
true
a110719cf4433362b9b45440b0ba455ebc7a3d64
SQL
electroly/sqlnotebook
/src/Tests/scripts/doc/lang_returning - Typical Use.sql
UTF-8
259
2.859375
3
[ "MIT" ]
permissive
-- https://sqlite.org/lang_returning.html CREATE TABLE t0( a INTEGER PRIMARY KEY, b DATE DEFAULT '2021-11-29 07:22:09', c INTEGER ); INSERT INTO t0(c) VALUES(5065768651967773830) RETURNING *; --output-- a,b,c 1,2021-11-29 07:22:09,5065768651967773830 -
true
88ed81ecd71a089b6c1ff509ac6831f0734fa9a1
SQL
heyday3/Database-Design-and-Modeling-NBA-Stat-Project
/team_10_NBAEasternConference_queries.sql
UTF-8
2,416
4.625
5
[]
no_license
/* Query #1 - atl_home_100 */ /** Show games where atlantic division teams are home and scoring more than 100 points**/ USE 2018_2019_nba_eastern_conf_upd; CREATE OR REPLACE VIEW atl_home_100 as SELECT CONCAT(team_city,' ', team_name) AS 'Home Team', team_2_score AS 'Score', game_id AS 'Game' FROM teams JOIN games on teams.team_arena = games.team_arena WHERE team_division = 'atlantic' and team_2_score >= 100 ORDER BY game_id /* Query #2 - commited_fouls */ /** Show total amount of infraction in each game where the away team beat the home team **/ USE 2018_2019_nba_eastern_conf_upd; CREATE VIEW committed_fouls AS SELECT distinct game_id AS 'Game', team_arena as 'Venue', Infractions FROM infractions JOIN infractions_games USING (infraction_type_id) JOIN games USING (game_id) JOIN (SELECT game_id, COUNT(game_id) AS Infractions FROM infractions_games GROUP BY game_id) fw USING (game_id) WHERE team_1_score > team_2_score /* Query #3 - full season */ /**Who in the NBA eastern confrence has played every game of the Season **/ USE 2018_2019_nba_eastern_conf_upd; CREATE OR REPLACE VIEW full_season AS SELECT CONCAT(player_fn, ' ', player_ln) AS 'Player Name', player_position FROM conference_roster JOIN player_stats USING (player_id) WHERE games_played = 82; /* Query #4 - three_year_contract */ /** What players positioned as a POWER FORWARD/PF have a contract that is greater than 3 years in length and how much they get paid per year in USD, ordered in by the most valuable contract to the least valuable **/ USE 2018_2019_nba_eastern_conf_upd; CREATE OR REPLACE VIEW player_three_year_contract AS SELECT concat(player_fn, ' ', player_ln) as 'Full Name', year_length, CONCAT('$', FORMAT(dollar_amount, 2)) as 'Contract Value' FROM contracts JOIN conference_roster ON conference_roster.player_id = contracts.player_id WHERE year_length > 3 and player_position = 'PF' ORDER BY (dollar_amount/year_length) DESC /* Query #5 - top_5_pg */ /**Show top 5 scoring point guards and their points per game**/ USE 2018_2019_nba_eastern_conf_upd; CREATE OR REPLACE VIEW top_5_pg as SELECT CONCAT(player_fn,' ', player_ln) AS 'Player Name', ROUND((total_points/games_played)) AS 'Points Per Game' FROM conference_roster JOIN player_stats ON conference_roster.player_id = player_stats.player_id WHERE player_position = 'PG' ORDER BY (total_points/games_played) DESC LIMIT 5
true
15e0f952dbde5e2bd25de9cbab8ac912ea7662b7
SQL
KenosSGI/org.kenos.idempiere.lbr
/org.kenos.idempiere.lbr.migration/migration-historic/000000/postgresql/7-360-trunk/109-FixServiceRPSCode.sql
UTF-8
1,312
2.875
3
[]
no_license
-- FIX RPS Code DELETE FROM AD_Ref_List WHERE AD_Reference_ID=1120009 AND Value='S1' ; DELETE FROM AD_Ref_List WHERE AD_Reference_ID=1120009 AND Value IN ('RPS', 'RP') ; INSERT INTO AD_Ref_List (AD_Ref_List_ID, AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, Updated, UpdatedBy, Value, Name, Description, AD_Reference_ID, ValidFrom, ValidTo, EntityType) VALUES(1121554, 0, 0, 'Y', '2015-03-22 15:50:31.0', 100, '2015-03-22 15:50:31.0', 100, 'S1', 'Nota Fiscal de Serviços Eletrônica (RPS)', NULL, 1120009, NULL, NULL, 'LBRA') ; INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1121554 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; UPDATE LBR_NotaFiscal SET LBR_NFModel='S1' WHERE LBR_NFModel IN ('RPS', 'RP') ; UPDATE C_DocType SET LBR_NFModel='S1' WHERE LBR_NFModel IN ('RPS', 'RP') ; SELECT Register_Migration_Script ('109-FixServiceRPSCode.sql') FROM DUAL ;
true
aa51a6640808517bd0d5035a1fac723f1d8a9e9c
SQL
FelixHTL-Leo/KiGa
/projectkiga/Database/kigaDB.sql
UTF-8
1,161
3.1875
3
[]
no_license
CREATE DATABASE kigaDB; USE kigaDB; create table users ( id int(11) NOT NULL, username varchar(50), password varchar(50), role varchar(1), groups varchar(10) ); create table messages ( id int(11) NOT NULL, details text NOT NULL, date_posted varchar(30), time_posted time, date_edited varchar(30), time_edited time, public varchar(5), groupPlaceing varchar(10) ); insert into users (id, username, password, role, groups) values('1', 'Christine', 'wert', '+', '-'); insert into users (id, username, password, role, groups) values('2', 'Klaus', 'wert', '-', 'Blue'); insert into users (id, username, password, role, groups) values('3', 'Peter', 'wert', '-', 'Red'); insert into messages (id, details, date_posted, time_posted, public, groupPlaceing) values('1', 'Hello Public', 'June 09, 2019', '19:08:52', 'yes', '-'); insert into messages (id, details, date_posted, time_posted, public, groupPlaceing) values('2', 'Hello Blue', 'June 09, 2019', '19:08:52', 'no', 'Blue'); insert into messages (id, details, date_posted, time_posted, public, groupPlaceing) values('3', 'Hello Red', 'June 09, 2019', '19:08:52', 'no', 'Red');
true
56cf169c86b38dace318bab53172b87d38c41de1
SQL
Kostiancheck/db_sem6
/sql/V7__create_exam_table.sql
UTF-8
633
2.90625
3
[]
no_license
CREATE TABLE Exam ( StudentOUTID UUID, Subject INT, School INT, TestStatus VARCHAR(256), Ball100 FLOAT, Ball12 FLOAT, Ball FLOAT, DPALevel VARCHAR(128) DEFAULT NULL, AdaptScale SMALLINT DEFAULT NULL, PRIMARY KEY (StudentOUTID, Subject), CONSTRAINT fk_student_exam FOREIGN KEY (StudentOUTID) REFERENCES Student (OUTID), CONSTRAINT fk_exam_school FOREIGN KEY (School) REFERENCES School (SchoolID), CONSTRAINT fk_exam_subject FOREIGN KEY (Subject) REFERENCES Subject (SubjectID) );
true
88851a30e0ff9f7184d4a8cde8039c093b2f0eda
SQL
kcnnn/bamazon
/bamazon.sql
UTF-8
2,045
3.65625
4
[]
no_license
DROP DATABASE IF EXISTS productsDB; -- DROP DATABASE IF EXISTS ice_creamDB; -- CREATE DATABASE productsDB; CREATE DATABASE productsDB; -- USE ice_creamDB; USE productsDB; -- CREATE TABLE products ( -- id INT NOT NULL AUTO_INCREMENT, -- flavor VARCHAR(45) NULL, -- price DECIMAL(10,2) NULL, -- quantity INT NULL, -- PRIMARY KEY (id) -- ); CREATE TABLE products ( id INT NOT NULL AUTO_INCREMENT, product_name VARCHAR(50) NULL, department_name VARCHAR(50) NULL, price DECIMAL(10) NULL, stock_quantity INT NULL, PRIMARY KEY (id) ); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book1", "books", 3, 10); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book2", "books", 5, 15); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book3", "books", 4, 45); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book4", "books", 65, 55); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book5", "books", 11, 12); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book6", "books", 9, 88); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book7", "books", 2, 14); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book8", "books", 45, 15); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book9", "books", 7, 35); INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES ("book10", "books", 43, 43); -- INSERT INTO products (flavor, price, quantity) -- VALUES ("chocolate", 3.10, 120); -- INSERT INTO products (flavor, price, quantity) -- VALUES ("strawberry", 3.25, 75); -- ### Alternative way to insert more than one row -- INSERT INTO products (flavor, price, quantity) -- VALUES ("vanilla", 2.50, 100), ("chocolate", 3.10, 120), ("strawberry", 3.25, 75);
true
a1f0a3ea3b6f1f2baf8bba66c2b9b61c1a42dba0
SQL
1512621/thesis
/script/Stage.sql
UTF-8
4,380
2.671875
3
[]
no_license
create table GHCN ( idGhcn varchar2(300) primary key, Jan numeric, Flag01 varchar2(50), Feb numeric, Flag02 varchar2(50), Mar numeric, Flag03 varchar2(50), Apr numeric, Flag04 varchar2(50), May numeric, Flag05 varchar2(50), June numeric, Flag06 varchar2(50), July numeric, Flag07 varchar(50), Aug numeric, Flag08 varchar2(50), Sep numeric, Flag09 varchar2(50), Oct numeric, Flag10 varchar2(50), Nov numeric, Flag11 varchar2(50), Dece numeric, Flag12 varchar2(50) ); / create table PRECIPTATION ( idPrecip varchar2(300) primary key, Jan numeric, Feb numeric, Mar numeric, Apr numeric, May numeric, June numeric, July numeric, Aug numeric, Sep numeric, Oct numeric, Nov numeric, Dece numeric ) / create table FOREST_TYPE ( IdType numeric GENERATED ALWAYS as identity(START WITH 1 INCREMENT BY 1) PRIMARY KEY, Elevation numeric, Aspect numeric, Slope numeric, HOR_DIST_TO_HYDROLOGY numeric, VER_DIST30_HYDROLOGY numeric, HOR_DIST30_ROADWAYS numeric, HILLSHADE_9AM numeric, HILLSHADE_NOON numeric, HILLSHADE_3PM numeric, HOR_DIST_TO_FIRE_POINTS numeric, WILDERNESS_AREAl VARCHAR2(3), WILDERNESS_AREA2 VARCHAR2(3), WILDERNESS_AREA3 VARCHAR2(3), WILDERNESS_AREA4 VARCHAR2(3), SOIL_TYPE1 VARCHAR2(3), SOIL_TYPE2 VARCHAR2(3), SOIL_TYPE3 VARCHAR2(3), SOIL_TYPE4 VARCHAR2(3), SOIL_TYPE5 VARCHAR2(3), SOIL_TYPE6 VARCHAR2(3), SOIL_TYPE7 VARCHAR2(3), SOIL_TYPE8 VARCHAR2(3), SOIL_TYPE9 VARCHAR2(3), SOIL_TYPE10 VARCHAR2(3), SOIL_TYPE11 VARCHAR2(3), SOIL_TYPE12 VARCHAR2(3), SOIL_TYPEl3 VARCHAR2(3), SOIL_TYPE14 VARCHAR2(3), SOIL_TYPEl5 VARCHAR2(3), SOIL_TYPE16 VARCHAR2(3), SOIL_TYPE17 vARCHAR2(3), SOIL_TYPE18 VARCHAR2(3), SOIL_TYPE19 vARCHAR2(3), SOIL_TYPE20 VARCHAR2(3), SOIL_TYPE21 VARCHAR2(3), SOIL_TYPE22 VARCHAR2(3), SOIL_TYPE23 VARCHAR2(3), SOIL_TYPE24 VARCHAR2(3), SOIL_TYPE25 VARCHAR2(3), SOIL_TYPE26 VARCHAR2(3), SOIL_TYPE27 VARCHAR2(3), SOIL_TYPE28 VARCHAR2(3), SOIL_TYPE29 VARCHAR2(3), SOIL_TYPE30 VARCHAR2(3), SOIL_TYPE31 VARCHAR2(3), SOIL_TYPE32 VARCHAR2(3), SOIL_TYPE33 VARCHAR2(3), SOIL_TYPE34 VARCHAR2(3), SOIL_TYPE35 vARCHAR2(3), SOIL_TYPE36 VARCHAR2(3), SOIL_TYPE37 VARCHAR2(3), SOIL_TYPE38 VARCHAR2(3), SOIL_TYPE39 VARCHAR2(3), SOIL_TYPE40 VARCHAR2(3), COVER_TYPE VARCHAR2(3) ) / create table WATER_QUALITY ( Id_Water_Quality numeric GENERATED ALWAYS as identity(START WITH 1 INCREMENT BY 1) PRIMARY KEY, Org_Id VARCHAR2(300), Org_Formal_Name VARCHAR2(300), Moni_Loc_Id VARCHAR2(300), Moni_Loc_Name VARCHAR2(300), Moni_Loc_Type_Name VARCHAR2(300), Moni_Loc_Des VARCHAR2(300), HUC_Eight_Digit_Code VARCHAR2(50), Dra_Area_Value numeric, Dra_Area_Code VARCHAR2(50), Con_Dra_Area_Value numeric, Con_Dra_Area_Code VARCHAR2(50), Latitude numeric, Longitude numeric, Source_Map_Scale numeric, Hor_Acc_Value numeric, Hor_Acc_Code VARCHAR2(50), Hor_Co_Me_Name VARCHAR2(300), Hor_Co_Re_Sys_Dat_Name VARCHAR2(300), Ver_Value numeric, Ver_Code VARCHAR2(300), Ver_Acc_Value numeric, Ver_Acc_Code VARCHAR2(300), Ver_Co_Me_Name VARCHAR2(300), Ver_Co_Re_Sys_Dat_Name VARCHAR2(300), Country_Code VARCHAR2(300), State_Code VARCHAR2(300), County_Code VARCHAR2(300), Aquifer_Name VARCHAR2(300), Formation_Type VARCHAR2(300), Aquifer_Type_Name VARCHAR2(300), Construction_Date VARCHAR2(300), Well_Depth_Value numeric, Well_Depth_Code VARCHAR2(300), Well_Hole_Depth_Value numeric, Well_Hole_Depth_Code VARCHAR2(300), Provider_Name VARCHAR2(300) ) / create table GHCN_V4_STATION ( IDSTATION VARCHAR2(300) primary key, LATITUDE VARCHAR2(50), LONGITUDE VARCHAR2(50), ELEVATION VARCHAR2(50), STATION_NAME VARCHAR2(300) ) / create table PRCP_V2_STATION ( IDSTATION VARCHAR2(300) primary key, STATION_NAME VARCHAR2(300), LATITUDE VARCHAR2(50), LONGITUDE VARCHAR2(50), ELEVATION VARCHAR2(50) ) / create table PRCP_V2_COUNTRY ( IDCOUNTRY VARCHAR2(20) primary key, COUNTRY_NAME VARCHAR2(1000) ) / create table GHCN_V4_COUNTRY ( IDCOUNTRY VARCHAR2(20) primary key, COUNTRY_NAME VARCHAR2(1000) ) /
true
5ff995ad55f06f794f321bbe3fc88a2999053868
SQL
NB-famous/student_cohort_Db
/4_queries/9_coh_avg_ass_dur.sql
UTF-8
991
4.15625
4
[]
no_license
/* Cohort Average Assistance Duration Calculate the average total duration of assistance requests for each cohort. -Use the previous query as a sub query to determine the duration per cohort. -Return a single row average_total_duration my wrong soln -> to create a sub query(nest) is to do it after the SELECT clause using paranthesis SELECT sum(completed_at - started_at) as average_total_duration FROM assistance_requests JOIN students ON students.id = assistance_requests.student_id JOIN cohorts ON cohorts.id = cohort_id WHERE average_total_duration = AVG(average_total_duration) ORDER BY average_total_duration; LHL soln */ SELECT avg (total_duration) as average_total_duration FROM ( SELECT cohorts.name as cohort, sum(completed_at-started_at) as total_duration FROM assistance_requests JOIN students ON students.id = student_id JOIN cohorts on cohorts.id = cohort_id GROUP BY cohorts.name ORDER BY total_duration ) as total_durations;
true
7829f49d33db34bd2e3a55dc41a87ab333694801
SQL
radtek/tensordev
/sql/db_audit_standard.sql
UTF-8
1,092
3.640625
4
[]
no_license
-- ----------------------------------------------------------------------------------- -- File Name : db_audit_standard.sql -- Description : Database auditing information (only if auditing is enabled) -- Requirements : Access to the DBA views. -- Call Syntax : @db_audit_standard -- Last Modified: 23/09/2013 -- ----------------------------------------------------------------------------------- prompt prompt Para listar todos os owners, digite TODOS ou senao entre com o nome especifico do owner prompt undefine owner COLUMN username FORMAT A10 COLUMN terminal FORMAT A30 COLUMN userhost FORMAT A30 COLUMN owner FORMAT A10 COLUMN obj_name FORMAT A10 COLUMN extended_timestamp FORMAT A35 COLUMN action_name FORMAT A20 SELECT username, terminal, userhost, extended_timestamp, owner, obj_name, action_name FROM dba_audit_trail WHERE owner = DECODE('&&owner', 'TODOS', owner, '&owner') ORDER BY extended_timestamp DESC;
true
87633aeb68478a919605c88cacb9181177ef7475
SQL
pamelaabreu/butter_backend
/local_seed.sql
UTF-8
8,629
3.53125
4
[]
no_license
DROP DATABASE IF EXISTS butter; CREATE DATABASE butter; \c butter; CREATE TABLE users ( id SERIAL PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), birthname VARCHAR NOT NULL, username VARCHAR UNIQUE NOT NULL, email VARCHAR UNIQUE NOT NULL, profile_img VARCHAR NULL, birthday VARCHAR NULL, joining_reason VARCHAR NULL, followers_number INT NULL, followings_number INT NULL, firebase_uid VARCHAR NOT NULL ); CREATE TABLE tags ( id SERIAL PRIMARY KEY, topic_name VARCHAR NOT NULL, image_url VARCHAR NOT NULL ); CREATE TABLE posts ( id SERIAL PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), user_posted_id INT NOT NULL, tag_id INT REFERENCES tags(id) NULL, content_url VARCHAR NOT NULL, title VARCHAR NULL, summary VARCHAR NULL, caption VARCHAR NULL, likes INT NULL, comments INT NULL, FOREIGN KEY (user_posted_id) REFERENCES users(id) ON DELETE CASCADE ); CREATE TABLE comments ( id SERIAL PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), user_commented_id INT NOT NULL, post_commented_id INT NOT NULL, comment VARCHAR NOT NULL, FOREIGN KEY (user_commented_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (post_commented_id) REFERENCES posts(id) ON DELETE CASCADE ); CREATE TABLE follows ( id SERIAL PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), user_follower_id INT NOT NULL, user_following_id INT NOT NULL, FOREIGN KEY (user_follower_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (user_following_id) REFERENCES users(id) ON DELETE CASCADE ); CREATE TABLE likes ( id SERIAL PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), user_like_id INT NOT NULL, post_like_id INT NOT NULL, FOREIGN KEY (user_like_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (post_like_id) REFERENCES posts(id) ON DELETE CASCADE ); CREATE TABLE saved_posts ( id SERIAL PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), user_saved_id INT NOT NULL, post_saved_id INT NOT NULL, FOREIGN KEY (user_saved_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (post_saved_id) REFERENCES posts(id) ON DELETE CASCADE ); CREATE TABLE notifications ( id SERIAL PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), user_action_id INT NOT NULL, notification_type VARCHAR NOT NULL, follower_action_id INT NULL, like_action_id INT NULL, comment_action_id INT NULL, user_received_action_id INT NOT NULL, post_action_id INT NULL, FOREIGN KEY (user_action_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (follower_action_id) REFERENCES follows(id) ON DELETE CASCADE, FOREIGN KEY (like_action_id) REFERENCES likes(id) ON DELETE CASCADE, FOREIGN KEY (comment_action_id) REFERENCES comments(id) ON DELETE CASCADE, FOREIGN KEY (user_received_action_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (post_action_id) REFERENCES posts(id) ON DELETE CASCADE ); INSERT INTO tags (topic_name, image_url) VALUES ('Shame', 'https://image.flaticon.com/icons/svg/89/89518.svg'), ('Sex', 'https://image.flaticon.com/icons/svg/1469/1469446.svg'), ('Insecurity', 'https://image.flaticon.com/icons/svg/1008/1008859.svg'), ('Relationships', 'https://image.flaticon.com/icons/svg/1189/1189170.svg'), ('Pleasure', 'https://image.flaticon.com/icons/svg/1469/1469432.svg'), ('Friendships', 'https://image.flaticon.com/icons/svg/1189/1189206.svg'), ('Contraceptions', 'https://image.flaticon.com/icons/svg/1012/1012725.svg'), ('Abortion', 'https://image.flaticon.com/icons/svg/113/113860.svg'), ('Pregnancy', 'https://image.flaticon.com/icons/svg/819/819058.svg'), ('Toys', 'https://image.flaticon.com/icons/svg/1463/1463353.svg'), ('Fantasy', 'https://image.flaticon.com/icons/svg/1504/1504140.svg'), ('Sexual Risks', 'https://image.flaticon.com/icons/svg/633/633571.svg'), ('STDS', 'https://image.flaticon.com/icons/svg/626/626513.svg'), ('Communication', 'https://image.flaticon.com/icons/svg/1078/1078011.svg'), ('HIV/AIDS', 'https://image.flaticon.com/icons/svg/35/35647.svg'), ('QTPOC', 'https://image.flaticon.com/icons/svg/55/55693.svg'), ('LATINOS', 'https://image.flaticon.com/icons/svg/1533/1533605.svg'), ('LGBTQIA', 'https://image.flaticon.com/icons/svg/1189/1189186.svg'), ('Sexual Health', 'https://image.flaticon.com/icons/svg/883/883360.svg'), ('Menstruation', 'https://image.flaticon.com/icons/svg/588/588084.svg'), ('Anal', 'https://image.flaticon.com/icons/svg/947/947768.svg'), ('Identity', 'https://image.flaticon.com/icons/svg/149/149240.svg'), ('Menopause', 'https://image.flaticon.com/icons/svg/263/263129.svg'), ('Dating', 'https://image.flaticon.com/icons/svg/1090/1090846.svg'), ('Technology', 'https://image.flaticon.com/icons/svg/149/149379.svg'), ('BDSM', 'https://image.flaticon.com/icons/svg/1538/1538781.svg'); INSERT INTO users (birthname, username, email, profile_img, birthday, joining_reason, followers_number, followings_number, firebase_uid) VALUES ('Pam', 'abrpam', 'pamela@butter.com', 'https://i.imgur.com/3hX8kUS.jpg', '1996-10-26', 'Talking about these conversations is important to me!', 2, 2, 'somethingToken'), ('Jo', 'designdyke', 'jo@jo.com', 'https://www.popsci.com/sites/popsci.com/files/styles/1000_1x_/public/images/2017/10/terrier-puppy.jpg?itok=rIgh3ArV&fc=50,50', '1996-08-11', 'This is so cool!', 1, 1, 'somethingToken'), ('Rupa', 'rupa1216', 'rupa@rupa.com', 'https://williamsburgvets.com/wp-content/uploads/2018/03/bulldog-puppy-pic.jpg', '1988-12-16', 'Why didnt this exist before?', 1, 1, 'somethingToken'), ('Thinx', 'thinx', 'thinx@thinx.com', 'https://mindbodygreen-res.cloudinary.com/images/w_767,q_auto:eco,f_auto,fl_lossy/ptr/QpbufLD/thinx.png', '1988-12-16', 'A company like ours want to be a part of this conversation', 0, 0, 'somethingToken'), ('Butter', 'butter', 'guest@butter.com', 'https://firebasestorage.googleapis.com/v0/b/butter-frontend.appspot.com/o/WS2vst3JyYXMKOexNqASM4RD3q92%2Fbutter_logo.png?alt=media&token=a78eb5b5-ce56-471b-b5c9-77323e903754', '1996-10-26', 'A place to be open about issues we struggle with is really important.', 0, 0, 'WS2vst3JyYXMKOexNqASM4RD3q92'); INSERT INTO posts (user_posted_id, tag_id, content_url, title, summary, caption, likes, comments) VALUES (4, 20, 'https://www.welltodoglobal.com/wp-content/uploads/2018/08/thinx_2-web.jpg', 'Thinx', 'Innovative period-proof underwear brand THINX has launched into the UK, continuing its mission to break taboos surrounding women’s intimate wellness.', 'Break women’s intimate taboos', 0, 0), (1, 3, 'http://b.parsons.edu/~abrep743/parsons/images/pam_d.jpg', 'Afraid', 'As much as Im smiling here, Im really anxious about never being perfect or good or accpeted.', 'Never being perfect enough',0, 2), (2, 7, 'https://static.wixstatic.com/media/335c4d_7636a4c8d6a0452fb6f96cb30de0a066~mv2_d_3724_5586_s_4_2.jpg/v1/fill/w_498,h_748,al_c,q_85,usm_0.66_1.00_0.01/335c4d_7636a4c8d6a0452fb6f96cb30de0a066~mv2_d_3724_5586_s_4_2.webp', 'DAM', 'Unlike any other dental dams on the market, our dams are wearable, silicone, ergonomic and tongue textured.', 'Ever used a DAM?',3, 2); INSERT INTO comments (user_commented_id, post_commented_id, comment) VALUES (1, 3, 'I WANT ONE! ✋'), (3, 3, 'ME TOO! 🙋🙋🙋'), (2, 2, 'YO UR BEYOND PERFECT CHILL OUT'), (3, 2, 'Dude IDK what u talking about ur flawless'); INSERT INTO follows (user_follower_id, user_following_id) VALUES (1, 3), (1, 2), (2, 1), (3, 1); INSERT INTO likes (user_like_id, post_like_id) VALUES (1, 3), (3, 3), (4, 3); INSERT INTO saved_posts (user_saved_id, post_saved_id) VALUES (1, 1), (1, 3), (3, 3); INSERT INTO notifications (user_action_id, user_received_action_id, notification_type, follower_action_id, like_action_id, comment_action_id, post_action_id) VALUES (1, 2, 'commented', NULL, NULL, 1, 3), (3, 2, 'commented', NULL, NULL, 2, 3), (2, 1, 'commented', NULL, NULL, 3, 2), (3, 1, 'commented', NULL, NULL, 4, 2), (1, 3, 'followed', 1, NULL, NULL, NULL), (1, 2, 'followed', 2, NULL, NULL, NULL), (2, 1, 'followed', 3, NULL, NULL, NULL), (3, 1, 'followed', 4, NULL, NULL, NULL), (1, 2, 'liked', NULL, 1, NULL, 3), (3, 2, 'liked', NULL, 2, NULL, 3), (4, 2, 'liked', NULL, 3, NULL, 3);
true
a25189aac736c00aa723aed8c5434fb7715a2535
SQL
msotiroff/Softuni-learning
/C# DB Module/DB Basics PL-SQL/Homeworks/07. DB-Basics-MSSQL-Subqueries-and-Joins/07.EmployeesWithProject/SQLQuery1.sql
UTF-8
291
4
4
[ "MIT" ]
permissive
SELECT TOP 5 e.EmployeeID, e.FirstName, p.Name AS ProjectName FROM Employees AS e INNER JOIN EmployeesProjects AS ep ON ep.EmployeeID = e.EmployeeID INNER JOIN Projects AS p ON p.ProjectID = ep.ProjectID AND p.StartDate > '08/13/2002' AND p.EndDate IS NULL ORDER BY e.EmployeeID
true
d683764aaafd4caea90274e02e2f54713ee83f40
SQL
patjan/erp
/sql/Orders.sql
UTF-8
4,510
3.25
3
[]
no_license
DROP TABLE IF EXISTS Orders; CREATE TABLE IF NOT EXISTS Orders ( id BIGINT NOT NULL AUTO_INCREMENT , updated_by BIGINT DEFAULT NULL , updated_at DATETIME DEFAULT NULL , status VARCHAR(32) DEFAULT 'Draft' , order_number VARCHAR(32) DEFAULT NULL , customer_id BIGINT DEFAULT NULL , product_id BIGINT DEFAULT NULL , color_id BIGINT DEFAULT NULL , ftp_id BIGINT DEFAULT NULL , machine_id BIGINT DEFAULT NULL , partner_id BIGINT DEFAULT NULL , osa_line_id BIGINT DEFAULT NULL , osa_number VARCHAR(32) DEFAULT NULL , labels_printed INT DEFAULT 0 , fpts_printed INT DEFAULT 0 , ops_printed INT DEFAULT 0 , ordered_at DATETIME DEFAULT NULL , needed_at DATETIME DEFAULT NULL , produced_at DATETIME DEFAULT NULL , quoted_units INT DEFAULT 0 , quoted_pieces INT DEFAULT 0 , ordered_pieces INT DEFAULT 0 , rejected_pieces INT DEFAULT 0 , produced_pieces INT DEFAULT 0 , checkout_pieces INT DEFAULT 0 , returned_pieces INT DEFAULT 0 , quoted_weight DECIMAL(10,2) DEFAULT 0 , ordered_weight DECIMAL(10,2) DEFAULT 0 , produced_weight DECIMAL(10,2) DEFAULT 0 , checkout_weight DECIMAL(10,2) DEFAULT 0 , returned_weight DECIMAL(10,2) DEFAULT 0 , location VARCHAR(4) DEFAULT NULL , PRIMARY KEY (id) , UNIQUE (order_number) , KEY customer (customer_id) , KEY machine (machine_id) , KEY partner (partner_id) , KEY product (product_id) , KEY color (color_id) , KEY ftp (ftp_id) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; INSERT Controls SET group_set='User Resources' , status='Active', sequence= 50, name='Orders', created_by=1, created_at=NOW(); INSERT Controls SET group_set='Ticket Categories' , status='Active', sequence= 50, name='Orders', created_by=1, created_at=NOW(); INSERT Controls SET group_set='System Numbers' , status='Active', sequence= 50, name='Next Order Number', value='100001', created_by=1, created_at=NOW(); ALTER TABLE Orders ADD COLUMN returned_weight DECIMAL(10,2) DEFAULT 0 AFTER produced_pieces; ALTER TABLE Orders ADD COLUMN checkout_weight DECIMAL(10,2) DEFAULT 0 AFTER produced_pieces; ALTER TABLE Orders ADD COLUMN ordered_weight DECIMAL(10,2) DEFAULT 0 AFTER produced_pieces; ALTER TABLE Orders CHANGE status status VARCHAR(32) DEFAULT 'Draft'; ALTER TABLE Orders ADD COLUMN ops_printed INT DEFAULT 0 AFTER labels_printed; ALTER TABLE Orders ADD COLUMN ftps_printed INT DEFAULT 0 AFTER labels_printed; ALTER TABLE Orders ADD COLUMN quot_line_id BIGINT DEFAULT NULL AFTER ftp_id; ALTER TABLE Orders ADD COLUMN quotation_number VARCHAR(32) DEFAULT NULL AFTER quot_line_id; ALTER TABLE Orders ADD COLUMN quoted_pieces INT DEFAULT 0 AFTER produced_at; ALTER TABLE Orders ADD COLUMN quoted_weight DECIMAL(10,2) DEFAULT 0 AFTER produced_pieces; ALTER TABLE Orders ADD COLUMN returned_pieces INT DEFAULT 0 AFTER produced_pieces; ALTER TABLE Orders ADD COLUMN checkout_pieces INT DEFAULT 0 AFTER produced_pieces; ALTER TABLE Orders ADD COLUMN quoted_units INT DEFAULT 0 AFTER produced_at; ALTER TABLE Orders ADD COLUMN produced_weight DECIMAL(10,2) DEFAULT 0 AFTER ordered_weight; ALTER TABLE Orders CHANGE quot_line_id osa_line_id BIGINT DEFAULT NULL; ALTER TABLE Orders CHANGE quotation_number osa_number VARCHAR(32) DEFAULT NULL; ALTER TABLE Orders ADD color_id BIGINT DEFAULT NULL AFTER product_id; ALTER TABLE Orders ADD location VARCHAR(4) DEFAULT NULL AFTER returned_weight; ALTER TABLE Orders ADD INDEX color (color_id ); ALTER TABLE Orders ADD INDEX ftp (ftp_id ); SELECT Orders.* , Customer.nick_name AS customer_name , Machine.name AS machine_name , Partner.nick_name AS partner_name , Color.color_name AS color_name , FTP.ftp_number AS ftp_number , Product.product_name AS product_name FROM Orders LEFT JOIN Contacts AS Customer ON Customer.id = Orders.customer_id LEFT JOIN Machines AS Machine ON Machine.id = Orders.machine_id LEFT JOIN Contacts AS Partner ON Partner.id = Orders.partner_id LEFT JOIN Products AS Product ON Product.id = Orders.product_id LEFT JOIN Colors AS Color ON Color.id = Orders.color_id LEFT JOIN FTPs AS FTP ON FTP.id = Orders.ftp_id WHERE Orders.id = 200384 SELECT COUNT(*) AS revised_pieces FROM Pieces WHERE order_id = $row['id'] AND status != "Active"
true
c7ff46f3690455718dd4c888f91f9a543f99d589
SQL
sreekarg/Data-Model-Query-languages
/project 2/q11.sql
UTF-8
2,914
3.546875
4
[]
no_license
with e as (select emp.dept_no,sal.salary,emp.emp_no from (select dept_no,emp_no from dept_emp)as emp inner join (select salaries.salary, salaries.emp_no from employees.salaries where salaries.to_date = '9999-01-01')as sal on emp.emp_no = sal.emp_no ) select departments.dept_name, emp_no, salary from e, employees.departments where e.salary >= all( select e2.salary from e as e2 where e2.dept_no = e.dept_no) and e.dept_no = departments.dept_no order by dept_name; #with #d1 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd001' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1), #d2 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd002' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1), #d3 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd003' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1), #d4 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd004' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1), #d5 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd005' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1), #d6 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd006' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1), #d7 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd007' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1), #d8 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd008' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1), #d9 as (select dept_no, salary, salaries.emp_no from employees.dept_emp, employees.salaries #where salaries.to_date = '9999-01-01' and dept_emp.dept_no = 'd009' and dept_emp.emp_no = salaries.emp_no #order by salary desc limit 1) #select departments.dept_name, emp.emp_no, emp.salary #from employees.departments, (select * from d1 union select * from d2 union select * from d3 union select * from d4 union select * from d5 union select * from d6 union select * from d7 union select * from d8 union select * from d9) as emp #where emp.dept_no = departments.dept_no #order by dept_name;
true
59d42f15403206a0942da9aee49d9ce7644798eb
SQL
nymtech/nym
/nym-api/migrations/20210722120000_create_initial_tables.sql
UTF-8
2,538
3.78125
4
[ "CC0-1.0", "Apache-2.0" ]
permissive
CREATE TABLE mixnode_details ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, owner VARCHAR NOT NULL, identity VARCHAR NOT NULL UNIQUE ); CREATE TABLE gateway_details ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, owner VARCHAR NOT NULL, identity VARCHAR NOT NULL UNIQUE ); create TABLE mixnode_historical_uptime ( mixnode_details_id INTEGER NOT NULL, -- 'YYYY-MM-DD' date VARCHAR NOT NULL, -- 24h uptimes for that day ipv4_uptime INTEGER NOT NULL, ipv6_uptime INTEGER NOT NULL, FOREIGN KEY (mixnode_details_id) REFERENCES mixnode_details (id) ); create table mixnode_ipv4_status ( mixnode_details_id INTEGER NOT NULL, up BOOLEAN NOT NULL, timestamp INTEGER NOT NULL, FOREIGN KEY (mixnode_details_id) REFERENCES mixnode_details (id) ); create table mixnode_ipv6_status ( mixnode_details_id INTEGER NOT NULL, up BOOLEAN NOT NULL, timestamp INTEGER NOT NULL, FOREIGN KEY (mixnode_details_id) REFERENCES mixnode_details (id) ); create TABLE gateway_historical_uptime ( gateway_details_id INTEGER NOT NULL, -- 'YYYY-MM-DD' date VARCHAR NOT NULL, -- 24h uptimes for that day ipv4_uptime INTEGER NOT NULL, ipv6_uptime INTEGER NOT NULL, FOREIGN KEY (gateway_details_id) REFERENCES gateway_details (id) ); create table gateway_ipv4_status ( gateway_details_id INTEGER NOT NULL, up BOOLEAN NOT NULL, timestamp INTEGER NOT NULL, FOREIGN KEY (gateway_details_id) REFERENCES gateway_details (id) ); create table gateway_ipv6_status ( gateway_details_id INTEGER NOT NULL, up BOOLEAN NOT NULL, timestamp INTEGER NOT NULL, FOREIGN KEY (gateway_details_id) REFERENCES gateway_details (id) ); -- indices for faster lookups CREATE INDEX `mixnode_ipv4_status_index` ON `mixnode_ipv4_status` (`mixnode_details_id`, `timestamp` desc); CREATE INDEX `mixnode_ipv6_status_index` ON `mixnode_ipv6_status` (`mixnode_details_id`, `timestamp` desc); CREATE INDEX `gateway_ipv4_status_index` ON `gateway_ipv4_status` (`gateway_details_id`, `timestamp` desc); CREATE INDEX `gateway_ipv6_status_index` ON `gateway_ipv6_status` (`gateway_details_id`, `timestamp` desc); CREATE INDEX `mixnode_identity_index` ON `mixnode_details` (`id`, `identity`); CREATE INDEX `gateway_identity_index` ON `gateway_details` (`id`, `identity`);
true
2b792d89d873450baeb6d281142f22e81eb5f220
SQL
GrandComicsDatabase/gcd-historical-archive
/database/0.4_little_nemo/migrate-0a.sql
UTF-8
1,277
3.84375
4
[]
no_license
SET SESSION sql_mode='STRICT_ALL_TABLES'; -- Allow for secret ballots (NULL voters, tracked through receipts instead). ALTER TABLE voting_vote MODIFY COLUMN voter_id integer default NULL; -- There should always be a quorum of at least one- no votes, no results. UPDATE voting_agenda SET quorum=1 WHERE quorum IS NULL; ALTER TABLE voting_agenda MODIFY COLUMN quorum integer NOT NULL default 1; ALTER TABLE voting_agenda_mailing_list ADD COLUMN is_primary tinyint(1) NOT NULL default 0; SET @policy_list=(SELECT id FROM voting_mailing_list WHERE address LIKE 'gcd-policy%'); SET @board_list=(SELECT id FROM voting_mailing_list WHERE address LIKE 'gcd-board%'); SET @rules_agenda=(SELECT id FROM voting_agenda WHERE name LIKE '%Rules'); SET @board_agenda=(SELECT id FROM voting_agenda WHERE name LIKE 'Board%'); UPDATE voting_agenda_mailing_list SET is_primary=1 WHERE (mailing_list_id=@policy_list AND agenda_id=@rules_agenda) OR (mailing_list_id=@board_list AND agenda_id=@board_agenda); ALTER TABLE voting_agenda_item CHANGE COLUMN open state tinyint(1) default NULL; -- Add the open flag, then set to one as all current topics are open. ALTER TABLE voting_topic ADD COLUMN open tinyint(1) NOT NULL default 0; UPDATE voting_topic SET open=1;
true
a9ce07ef7256815ccfe5393067afb92f603f3b46
SQL
mithridatem/task
/task2.sql
UTF-8
1,742
3.796875
4
[]
no_license
CREATE TABLE `task` ( `id_task` int(11) NOT NULL, `name_task` varchar(50) NOT NULL, `content_task` text NOT NULL, `date_task` date NOT NULL, `valid_task` tinyint(1) DEFAULT '0', `id_util` int(11) DEFAULT NULL, `id_type` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `type` ( `id_type` int(11) NOT NULL, `name_type` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `utilisateur` ( `id_util` int(11) NOT NULL, `name_util` varchar(50) NOT NULL, `first_name_util` varchar(50) NOT NULL, `login_util` varchar(50) NOT NULL, `mdp_util` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `utilisateur2` ( `id_util` int(50) NOT NULL, `nom_util` varchar(50) NOT NULL, `first_name_util` varchar(50) NOT NULL, `login_util` varchar(50) NOT NULL, `mdp_util` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `task` ADD PRIMARY KEY (`id_task`), ADD KEY `task_utilisateur_FK` (`id_util`), ADD KEY `task_type0_FK` (`id_type`); ALTER TABLE `type` ADD PRIMARY KEY (`id_type`); ALTER TABLE `utilisateur` ADD PRIMARY KEY (`id_util`); ALTER TABLE `utilisateur2` ADD PRIMARY KEY (`id_util`); ALTER TABLE `task` MODIFY `id_task` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `type` MODIFY `id_type` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `utilisateur` MODIFY `id_util` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `utilisateur2` MODIFY `id_util` int(50) NOT NULL AUTO_INCREMENT; ALTER TABLE `task` ADD CONSTRAINT `task_type0_FK` FOREIGN KEY (`id_type`) REFERENCES `type` (`id_type`), ADD CONSTRAINT `task_utilisateur_FK` FOREIGN KEY (`id_util`) REFERENCES `utilisateur` (`id_util`);
true
8115661c09a03d752fd200ac5a001f6ccbe46294
SQL
kavishkaHerath/HEATHCARE_PAF_PRACTICAL
/db/helthcare.sql
UTF-8
2,130
3.15625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: May 06, 2020 at 05:48 PM -- Server version: 10.4.11-MariaDB -- PHP Version: 7.4.3 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: `helthcare` -- -- -------------------------------------------------------- -- -- Table structure for table `appointment` -- CREATE TABLE `appointment` ( `AppointmentId` int(10) NOT NULL, `PatientName` varchar(50) NOT NULL, `DoctorName` varchar(50) NOT NULL, `HosptlName` varchar(50) NOT NULL, `phone` varchar(25) NOT NULL, `email` varchar(50) NOT NULL, `date` varchar(20) NOT NULL, `time` varchar(10) NOT NULL, `charge` float(8,2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `appointment` -- INSERT INTO `appointment` (`AppointmentId`, `PatientName`, `DoctorName`, `HosptlName`, `phone`, `email`, `date`, `time`, `charge`) VALUES (118, 'Ravindu Kavishka', 'DR Dilakshika Perera', 'Ceymed Health care', '0718908486', 'hmravindu@gmail.com', '2020-05-30', '01:00', 5000.00), (120, 'Chamara Bandara', 'DR Dilakshika Perera', 'Asiri Hospital', '0756859612', 'chamara@gmail.com', '2020-06-18', '16:50', 1500.00), (121, 'Amal Perera ', 'DR Dilakshika Perera', 'Nawaloka Hospitals Limited', '0715896262', 'hmravindu@gmail.com', '2020-08-30', '20:30', 4500.00); -- -- Indexes for dumped tables -- -- -- Indexes for table `appointment` -- ALTER TABLE `appointment` ADD PRIMARY KEY (`AppointmentId`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `appointment` -- ALTER TABLE `appointment` MODIFY `AppointmentId` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=122; 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
eff8c00754a442d16bc8fd538b5ddef3dc03e71d
SQL
muntaza/Open_Persediaan
/sql1_persediaan/tahun.sql
UTF-8
346
2.734375
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
DROP VIEW IF EXISTS view_tahun CASCADE; CREATE VIEW view_tahun AS select 2015 as tahun union select 2016 as tahun union select 2017 as tahun union select 2018 as tahun union select 2019 as tahun union select 2020 as tahun ; GRANT ALL PRIVILEGES ON view_tahun TO lap_kabupaten; REVOKE INSERT, UPDATE, DELETE ON view_tahun FROM lap_kabupaten;
true
6bca172bf02d3331b3ead7ee74040d0d72e57377
SQL
holmanjr/sql-challenge
/blog.sql
UTF-8
292
2.6875
3
[]
no_license
DROP DATABASE IF EXISTS blog; CREATE DATABASE blog; \c blog; CREATE TABLE post ( ID SERIAL PRIMARY KEY, title VARCHAR, content VARCHAR ); INSERT INTO post (title, content) VALUES ('First Post', 'This is my first blog post. It is made just to test out that my DB is working.');
true
85630b53c242ff5ef1e08ff0cdabbf7882bc38df
SQL
devNoiseConsulting/InnerSphereAtlas-SiteMap
/sql/slug.sql
UTF-8
797
3.421875
3
[ "MIT" ]
permissive
SELECT 'Planets' FROM dual; UPDATE planet P1, planet P2 SET P1.slug = CONCAT_WS('/', P2.planet_id, REPLACE(LOWER(TRIM(P2.name)), ' ', '-')) WHERE P2.planet_id = P1.planet_id; SELECT 'Factories' FROM dual; UPDATE factory F1, factory F2 SET F1.slug = CONCAT_WS('/', F2.factory_id, REPLACE(LOWER(TRIM(F2.name)), ' ', '-')) WHERE F2.factory_id = F1.factory_id; SELECT 'Novels' FROM dual; UPDATE novel F1, novel F2 SET F1.slug = CONCAT_WS('/', F2.novel_id, REPLACE(LOWER(TRIM(F2.title)), ' ', '-')) WHERE F2.novel_id = F1.novel_id; SELECT 'Product Types' FROM dual; UPDATE product_type P1, product_type P2 SET P1.slug = CONCAT_WS('/', P2.product_type_id, REPLACE(LOWER(CONCAT_WS('-', TRIM(P2.component_type), TRIM(P2.product_type))), ' ', '-')) WHERE P2.product_type_id = P1.product_type_id;
true
f695c2bc8aa60fb4ff8358e1e696e97817f01d14
SQL
tri7/dbv
/data/schema/metadados_obras_BEFORE_INSERT.sql
UTF-8
652
2.953125
3
[]
no_license
CREATE DEFINER=`root`@`localhost` TRIGGER `cpm`.`metadados_obras_BEFORE_INSERT` BEFORE INSERT ON `cpm`.`metadados_obras` FOR EACH ROW begin declare proc_tit tinyint(1) default 0; declare proc_imdb_link tinyint(1) default 0; declare proc_classificacao_etaria_id tinyint(1) default 0; select new.titulo_pt is not null, new.imdb_link is not null, new.classificacao_etaria_id is not null into proc_tit, proc_imdb_link, proc_classificacao_etaria_id; set @service_meta := 0; if new.service = 1 or (proc_tit = 0 and proc_imdb_link = 0 and proc_classificacao_etaria_id = 0) then set new.service := 0; set @service_meta := 1; end if; end
true
fb1af5d2c8cea5fbf91503c9bec91d1ed2dee951
SQL
crodriguezn/crossfit-milagro
/_files/DB/version/version_2.sql
UTF-8
6,694
3.1875
3
[]
no_license
/************ Remove Foreign Keys ***************/ ALTER TABLE catalog DROP CONSTRAINT catalog_id_catalog_type_fkey; ALTER TABLE company_branch DROP CONSTRAINT company_branch_id_ciudad_fkey; ALTER TABLE company_branch DROP CONSTRAINT company_branch_id_company_fkey; ALTER TABLE module DROP CONSTRAINT module_id_parent_fkey; ALTER TABLE permission DROP CONSTRAINT permission_id_module_fkey; ALTER TABLE person DROP CONSTRAINT person_id_ciudad_fkey; ALTER TABLE profile DROP CONSTRAINT profile_id_rol_fkey; ALTER TABLE profile_permission DROP CONSTRAINT profile_permission_id_permission_fkey; ALTER TABLE profile_permission DROP CONSTRAINT profile_permission_id_profile_fkey; ALTER TABLE rol_module DROP CONSTRAINT rol_module_id_module_fkey; ALTER TABLE rol_module DROP CONSTRAINT rol_module_id_rol_fkey; ALTER TABLE session_activity DROP CONSTRAINT session_activity_id_user_profile_fkey; ALTER TABLE "user" DROP CONSTRAINT user_id_person_fkey; ALTER TABLE user_log DROP CONSTRAINT user_log_id_user_fkey; ALTER TABLE user_profile DROP CONSTRAINT user_profile_id_profile_fkey; ALTER TABLE user_profile DROP CONSTRAINT user_profile_id_user_fkey; ALTER TABLE user_profile__company_branch DROP CONSTRAINT user_profile__company_branch_id_company_branch_fkey; ALTER TABLE user_profile__company_branch DROP CONSTRAINT user_profile__company_branch_id_user_profile_fkey; /************ Update: Tables ***************/ /******************** Rebuild Table: configuration_system ************************ Reasons: Column: logo Data type length changed. Server Column: logo, DT=VarChar, L=250, COM=, N=true, AN=false, DF=, SC=, SI=true, EN=, ARR=false. Design Column: logo, DT=VarChar, L=450, COM=, N=true, AN=false, DF=, SC=, SI=true, EN=, ARR=false. *****************************************************************************/ /* Rename: configuration_system */ ALTER TABLE configuration_system RENAME TO configuration_system_old; /* Build Table Structure */ CREATE TABLE configuration_system ( id NUMERIC(20, 0) NOT NULL, name_system VARCHAR(250) NOT NULL, logo VARCHAR(450) NULL, session_time_limit_min NUMERIC(20, 0) NULL, session_time_limit_max NUMERIC(20, 0) NULL, "isSaveBinnacle" SMALLINT NULL ) WITHOUT OIDS; /* Repopulate Table Data */ INSERT INTO configuration_system (id, name_system, logo, session_time_limit_min, session_time_limit_max, "isSaveBinnacle") SELECT id, name_system, logo, session_time_limit_min, session_time_limit_max, "isSaveBinnacle" FROM configuration_system_old; /* Remove Temp Table */ DROP TABLE configuration_system_old CASCADE; /* Add Primary Key */ ALTER TABLE configuration_system ADD CONSTRAINT pkconfiguration_system PRIMARY KEY (id); /* Add Indexes */ CREATE INDEX "configuration_system_id_Idx" ON configuration_system USING btree (id); CREATE INDEX "configuration_system_name_system_Idx" ON configuration_system USING btree (name_system); /************ Add Foreign Keys ***************/ /* Add Foreign Key: fk_catalog_catalog_type */ ALTER TABLE catalog ADD CONSTRAINT fk_catalog_catalog_type FOREIGN KEY (id_catalog_type) REFERENCES catalog_type (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_company_branch_ciudad */ ALTER TABLE company_branch ADD CONSTRAINT fk_company_branch_ciudad FOREIGN KEY (id_ciudad) REFERENCES ciudad (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_company_branch_company */ ALTER TABLE company_branch ADD CONSTRAINT fk_company_branch_company FOREIGN KEY (id_company) REFERENCES company (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_module_module */ ALTER TABLE module ADD CONSTRAINT fk_module_module FOREIGN KEY (id_parent) REFERENCES module (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_permission_module */ ALTER TABLE permission ADD CONSTRAINT fk_permission_module FOREIGN KEY (id_module) REFERENCES module (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_person_ciudad */ ALTER TABLE person ADD CONSTRAINT fk_person_ciudad FOREIGN KEY (id_ciudad) REFERENCES ciudad (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_profile_rol */ ALTER TABLE profile ADD CONSTRAINT fk_profile_rol FOREIGN KEY (id_rol) REFERENCES rol (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_profile_permission_permission */ ALTER TABLE profile_permission ADD CONSTRAINT fk_profile_permission_permission FOREIGN KEY (id_permission) REFERENCES permission (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_profile_permission_profile */ ALTER TABLE profile_permission ADD CONSTRAINT fk_profile_permission_profile FOREIGN KEY (id_profile) REFERENCES profile (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_rol_module_module */ ALTER TABLE rol_module ADD CONSTRAINT fk_rol_module_module FOREIGN KEY (id_module) REFERENCES module (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_rol_module_rol */ ALTER TABLE rol_module ADD CONSTRAINT fk_rol_module_rol FOREIGN KEY (id_rol) REFERENCES rol (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_session_activity_user_profile */ ALTER TABLE session_activity ADD CONSTRAINT fk_session_activity_user_profile FOREIGN KEY (id_user_profile) REFERENCES user_profile (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_user_person */ ALTER TABLE "user" ADD CONSTRAINT fk_user_person FOREIGN KEY (id_person) REFERENCES person (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_user_log_user */ ALTER TABLE user_log ADD CONSTRAINT fk_user_log_user FOREIGN KEY (id_user) REFERENCES "user" (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_user_profile_profile */ ALTER TABLE user_profile ADD CONSTRAINT fk_user_profile_profile FOREIGN KEY (id_profile) REFERENCES profile (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_user_profile_user */ ALTER TABLE user_profile ADD CONSTRAINT fk_user_profile_user FOREIGN KEY (id_user) REFERENCES "user" (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_user_profile__company_branch_company_branch */ ALTER TABLE user_profile__company_branch ADD CONSTRAINT fk_user_profile__company_branch_company_branch FOREIGN KEY (id_company_branch) REFERENCES company_branch (id) ON UPDATE NO ACTION ON DELETE NO ACTION; /* Add Foreign Key: fk_user_profile__company_branch_user_profile */ ALTER TABLE user_profile__company_branch ADD CONSTRAINT fk_user_profile__company_branch_user_profile FOREIGN KEY (id_user_profile) REFERENCES user_profile (id) ON UPDATE NO ACTION ON DELETE NO ACTION;
true
e4e7aa91537c6aa470a5a1493778850ecc3c8dcb
SQL
anatole72/sql_scripts
/sga_size.sql
UTF-8
343
2.90625
3
[]
no_license
ttitle 'COMPUTE SUM OF VALUE kbval ON REPORT' skip 2 clear breaks clear computes clear columns column name format a20 heading "SGA Segment" column value format 999,999,999,990 heading "Size|(Bytes)" column kbval format 999,999,990.9 heading "Size|(Kb)" break on report select name,value,round(value/1024,1) kbval from v$sga;
true
558fe6e6ca93cc737434b7e9a4d79fd2de8068de
SQL
robbyn/fantastico
/conf/update-1.04.sql
UTF-8
729
3.28125
3
[]
no_license
charset utf8 create table payments ( ID varchar(24) not null, PARENT_ID varchar(24), USER_ID integer, EVENT_ID integer, DATETIME datetime not null, AMOUNT decimal(15,2) not null, DETAILS longtext, primary key (ID) ); alter table payments add index FK526A0F2DFEC4B6B (EVENT_ID), add constraint FK526A0F2DFEC4B6B foreign key (EVENT_ID) references events (ID); alter table payments add index FK526A0F2DD6347FC9 (USER_ID), add constraint FK526A0F2DD6347FC9 foreign key (USER_ID) references users (ID); alter table payments add index FK526A0F2D29EEC287 (PARENT_ID), add constraint FK526A0F2D29EEC287 foreign key (PARENT_ID) references payments (ID);
true
1a78305caf12a5ef7441c3f66a02a9565758999c
SQL
Danboru/Twitter-Tweet
/PBP_A_TTS_672014113.sql
UTF-8
1,433
2.734375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 3.4.10.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Oct 18, 2016 at 09:32 AM -- Server version: 5.5.20 -- PHP Version: 5.3.10 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `pbp_a_tts_672014113` -- -- -------------------------------------------------------- -- -- Table structure for table `tbl_tweet` -- CREATE TABLE IF NOT EXISTS `tbl_tweet` ( `tweet_id` int(11) NOT NULL AUTO_INCREMENT, `tweet` varchar(500) NOT NULL, PRIMARY KEY (`tweet_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ; -- -- Dumping data for table `tbl_tweet` -- INSERT INTO `tbl_tweet` (`tweet_id`, `tweet`) VALUES (17, 'Masih sedikit kesulitan dalam menerapkan semua fitur CRUD dengan metode AJAX . . :)\n\nMasih coba buat yang UPDAE dan DELETE dengan AJAX . . . input dan view sudah menggunakan AJAX'), (15, 'Kwitansi :D'), (16, 'Test Auto reload , , without pressing button.'), (14, 'Kasbon , , , heheh :)'); /*!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
6db8e732677efb7f36187c67aca976c35476a40d
SQL
ardidagol/Package-Oracle
/2020/VMT - Vementor/XXVMT_RFP_INVOICE_RPT_V.sql
UTF-8
18,126
2.84375
3
[]
no_license
/* Formatted on 10/5/2020 1:26:59 PM (QP5 v5.256.13226.35538) */ CREATE OR REPLACE VIEW XXVMT_RFP_INVOICE_RPT_V AS SELECT RFP_NO, SUPPLIER_NAME, BATCH_ID, ORG_ID, INVOICE_BATCH_NAME, INVOICE_DUE, TOTAL_PAYMENT, PAID_TO, REQUESTOR, CREATOR, INVOICE_AMOUNT, VAT_REGISTRATION_NUM, BANK_NAME, BENEFICIARY_NAME, ACCOUNT_NUMBER, INVOICE_ID, INVOICE_NUM, INVOICE_DATE, GL_DATE, EXCHANGE_RATE, EXCHANGE_DATE, EXCHANGE_RATE_TYPE, INVOICE_CURRENCY_CODE, NPWP, TGL_FAKTUR, ATTRIBUTE_CATEGORY, DESCRIPTION, TERMS_DUE_DAYS, BP_NUMBER, PPN_BASE_AMOUNT, PPN_AMOUNT, SUPPLIER_SITE, PO_NUM, PO_DATE, RCV_NUM, RCV_DATE, APPROVAL_STATUS, PROJECT_CODE, AMOUNT_DR, AMOUNT_CR, ACCOUNTED_DR, ACCOUNTED_CR, GL_ACCOUNT, SEGMENT2, SEGMENT3, SEGMENT5, SEGMENT6, PAYMENT_STATUS_FLAG, APPROVAL_STATUS_GL FROM ( SELECT AB.ATTRIBUTE1 RFP_NO, HP.PARTY_NAME SUPPLIER_NAME, AB.BATCH_ID, AI.ORG_ID, AB.BATCH_NAME INVOICE_BATCH_NAME, APSA.DUE_DATE INVOICE_DUE, SUM (AI.INVOICE_AMOUNT) TOTAL_PAYMENT, DECODE (AB.ATTRIBUTE2, NULL, HP.PARTY_NAME, AB.ATTRIBUTE2, AB.ATTRIBUTE2) PAID_TO, AB.ATTRIBUTE3 REQUESTOR, FU.USER_NAME CREATOR, APS.VAT_REGISTRATION_NUM, IEB.BANK_NAME Bank_Name, IEBA.BANK_ACCOUNT_NAME Beneficiary_Name, IEBA.BANK_ACCOUNT_NUM Account_Number, AI.INVOICE_ID, AI.INVOICE_NUM, AI.INVOICE_DATE, AI.INVOICE_AMOUNT, AI.GL_DATE, AI.EXCHANGE_RATE, AI.EXCHANGE_DATE, AI.EXCHANGE_RATE_TYPE, AI.INVOICE_CURRENCY_CODE, AI.SUPPLIER_TAX_INVOICE_NUMBER NPWP, AI.SUPPLIER_TAX_INVOICE_DATE TGL_FAKTUR, AI.ATTRIBUTE_CATEGORY, AI.DESCRIPTION, ATL.DUE_DAYS TERMS_DUE_DAYS, ACA.ATTRIBUTE3 BP_NUMBER, TO_CHAR (AI.ATTRIBUTE3, '9,999,999,999,999.9999') PPN_BASE_AMOUNT, TO_CHAR (AI.ATTRIBUTE4, '999,999,999,999.9999') PPN_AMOUNT, POV.VENDOR_SITE_CODE SUPPLIER_SITE, PHA.SEGMENT1 PO_NUM, PHA.CREATION_DATE PO_DATE, RSH.RECEIPT_NUM RCV_NUM, RT.TRANSACTION_DATE RCV_DATE, AP_INVOICES_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) APPROVAL_STATUS, NULL PROJECT_CODE, NULL AMOUNT_DR, SUM (NVL (AI.INVOICE_AMOUNT, 0)) AMOUNT_CR, NULL ACCOUNTED_DR, DECODE (AI.INVOICE_CURRENCY_CODE, 'IDR', SUM (NVL (AI.INVOICE_AMOUNT, 0)), SUM (NVL (AI.BASE_AMOUNT, 0))) ACCOUNTED_CR, GLCC.SEGMENT1 || '-' || GLCC.SEGMENT2 || '-' || GLCC.SEGMENT3 || '-' || GLCC.SEGMENT4 || '-' || GLCC.SEGMENT5 || '-' || GLCC.SEGMENT6 || '-' || GLCC.SEGMENT7 GL_ACCOUNT, GLCC.SEGMENT2 SEGMENT2, GLCC.SEGMENT3 SEGMENT3, GLCC.SEGMENT5 SEGMENT5, GLCC.SEGMENT6 SEGMENT6, AI.PAYMENT_STATUS_FLAG, AP_INVOICES_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) APPROVAL_STATUS_GL FROM AP.AP_INVOICES_ALL AI, AP.AP_BATCHES_ALL AB, AP.AP_PAYMENT_SCHEDULES_ALL APSA, AR.HZ_PARTIES HP, AP.AP_TERMS_LINES ATL, AP.AP_INVOICE_PAYMENTS_ALL AIPA, AP.AP_CHECKS_ALL ACA, FND_USER FU, AP_SUPPLIERS APS, IBY_EXT_BANK_ACCOUNTS IEBA, IBY_EXT_BANKS_V IEB, APPS.PO_VENDOR_SITES_ALL POV, AP_INVOICE_LINES_ALL AILA, PO_HEADERS_ALL PHA, RCV_TRANSACTIONS RT, RCV_SHIPMENT_HEADERS RSH, GL.GL_CODE_COMBINATIONS GLCC WHERE AI.BATCH_ID = AB.BATCH_ID AND AI.PARTY_ID = HP.PARTY_ID AND AB.CREATED_BY = FU.USER_ID AND AI.VENDOR_ID = APS.VENDOR_ID AND APSA.INVOICE_ID = AI.INVOICE_ID AND POV.VENDOR_ID = AI.VENDOR_ID AND POV.VENDOR_SITE_ID = AI.VENDOR_SITE_ID AND AI.TERMS_ID = ATL.TERM_ID AND AI.INVOICE_ID = AIPA.INVOICE_ID(+) AND AIPA.CHECK_ID = ACA.CHECK_ID(+) AND AP_INVOICES_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) NOT IN ('CANCELLED') AND AP_INVOICES_UTILITY_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) NOT IN ('CANCELLED') AND AI.ACCTS_PAY_CODE_COMBINATION_ID = GLCC.CODE_COMBINATION_ID AND IEBA.EXT_BANK_ACCOUNT_ID(+) = AI.EXTERNAL_BANK_ACCOUNT_ID AND IEBA.BANK_ID = IEB.BANK_PARTY_ID(+) AND AI.INVOICE_ID = AILA.INVOICE_ID(+) AND AILA.PO_HEADER_ID = PHA.PO_HEADER_ID(+) AND AILA.RCV_TRANSACTION_ID = RT.TRANSACTION_ID(+) AND RT.SHIPMENT_HEADER_ID = RSH.SHIPMENT_HEADER_ID(+) GROUP BY AB.ATTRIBUTE1, HP.PARTY_NAME, AB.BATCH_ID, AI.ORG_ID, AB.BATCH_NAME, APSA.DUE_DATE, AI.INVOICE_CURRENCY_CODE, DECODE (AB.ATTRIBUTE2, NULL, HP.PARTY_NAME, AB.ATTRIBUTE2, AB.ATTRIBUTE2), AB.ATTRIBUTE3, FU.USER_NAME, AI.INVOICE_AMOUNT, APS.VAT_REGISTRATION_NUM, IEB.BANK_NAME, IEBA.BANK_ACCOUNT_NAME, IEBA.BANK_ACCOUNT_NUM, AI.INVOICE_ID, AI.INVOICE_NUM, AI.INVOICE_DATE, AI.GL_DATE, AI.EXCHANGE_RATE, AI.EXCHANGE_DATE, AI.EXCHANGE_RATE_TYPE, AI.INVOICE_CURRENCY_CODE, AI.SUPPLIER_TAX_INVOICE_NUMBER, AI.SUPPLIER_TAX_INVOICE_DATE, AI.ATTRIBUTE_CATEGORY, ACA.ATTRIBUTE3, TO_CHAR (AI.ATTRIBUTE3, '9,999,999,999,999.9999'), TO_CHAR (AI.ATTRIBUTE4, '999,999,999,999.9999'), POV.VENDOR_SITE_CODE, PHA.SEGMENT1, PHA.CREATION_DATE, RSH.RECEIPT_NUM, RT.TRANSACTION_DATE, AI.DESCRIPTION, ATL.DUE_DAYS, GLCC.SEGMENT1, GLCC.SEGMENT2, GLCC.SEGMENT3, GLCC.SEGMENT4, GLCC.SEGMENT5, GLCC.SEGMENT6, GLCC.SEGMENT7, AI.PAYMENT_STATUS_FLAG, AP_INVOICES_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) UNION SELECT AB.ATTRIBUTE1 RFP_NO, HP.PARTY_NAME SUPPLIER_NAME, AB.BATCH_ID, AI.ORG_ID, AB.BATCH_NAME INVOICE_BATCH_NAME, APSA.DUE_DATE INVOICE_DUE, SUM (AI.INVOICE_AMOUNT) TOTAL_PAYMENT, DECODE (AB.ATTRIBUTE2, NULL, HP.PARTY_NAME, AB.ATTRIBUTE2, AB.ATTRIBUTE2) PAID_TO, AB.ATTRIBUTE3 REQUESTOR, FU.USER_NAME CREATOR, APS.VAT_REGISTRATION_NUM, IEB.BANK_NAME Bank_Name, IEBA.BANK_ACCOUNT_NAME Beneficiary_Name, IEBA.BANK_ACCOUNT_NUM Account_Number, AI.INVOICE_ID, AI.INVOICE_NUM, AI.INVOICE_DATE, AI.INVOICE_AMOUNT, AI.GL_DATE, AI.EXCHANGE_RATE, AI.EXCHANGE_DATE, AI.EXCHANGE_RATE_TYPE, AI.INVOICE_CURRENCY_CODE, AI.SUPPLIER_TAX_INVOICE_NUMBER NPWP, AI.SUPPLIER_TAX_INVOICE_DATE TGL_FAKTUR, AI.ATTRIBUTE_CATEGORY, AI.DESCRIPTION, ATL.DUE_DAYS TERMS_DUE_DAYS, ACA.ATTRIBUTE3 BP_NUMBER, TO_CHAR (AI.ATTRIBUTE3, '9,999,999,999,999.9999') PPN_BASE_AMOUNT, TO_CHAR (AI.ATTRIBUTE4, '999,999,999,999.9999') PPN_AMOUNT, POV.VENDOR_SITE_CODE SUPPLIER_SITE, PHA.SEGMENT1 PO_NUM, PHA.CREATION_DATE PO_DATE, RSH.RECEIPT_NUM RCV_NUM, RT.TRANSACTION_DATE RCV_DATE, AP_INVOICES_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) APPROVAL_STATUS, AILA.ATTRIBUTE8 PROJECT_CODE, SUM (NVL (AID.AMOUNT, 0)) AMOUNT_DR, NULL AMOUNT_CR, DECODE (AI.INVOICE_CURRENCY_CODE, 'IDR', SUM (NVL (AID.AMOUNT, 0)), SUM (NVL (AID.BASE_AMOUNT, 0))) ACCOUNTED_DR, NULL ACCOUNTED_CR, GLCC.SEGMENT1 || '-' || GLCC.SEGMENT2 || '-' || GLCC.SEGMENT3 || '-' || GLCC.SEGMENT4 || '-' || GLCC.SEGMENT5 || '-' || GLCC.SEGMENT6 || '-' || GLCC.SEGMENT7 GL_ACCOUNT, GLCC.SEGMENT2 SEGMENT2, GLCC.SEGMENT3 SEGMENT3, GLCC.SEGMENT5 SEGMENT5, GLCC.SEGMENT6 SEGMENT6, AI.PAYMENT_STATUS_FLAG, AP_INVOICES_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) APPROVAL_STATUS_GL FROM AP.AP_INVOICES_ALL AI, AP.AP_BATCHES_ALL AB, AP.AP_PAYMENT_SCHEDULES_ALL APSA, AR.HZ_PARTIES HP, AP.AP_TERMS_LINES ATL, AP.AP_INVOICE_PAYMENTS_ALL AIPA, AP.AP_CHECKS_ALL ACA, FND_USER FU, AP_SUPPLIERS APS, IBY_EXT_BANK_ACCOUNTS IEBA, IBY_EXT_BANKS_V IEB, APPS.PO_VENDOR_SITES_ALL POV, AP.AP_INVOICE_LINES_ALL AILA, PO_HEADERS_ALL PHA, RCV_TRANSACTIONS RT, RCV_SHIPMENT_HEADERS RSH, AP.AP_INVOICE_DISTRIBUTIONS_ALL AID, GL.GL_CODE_COMBINATIONS GLCC -- DR_CR WHERE AI.BATCH_ID = AB.BATCH_ID AND AI.PARTY_ID = HP.PARTY_ID AND AB.CREATED_BY = FU.USER_ID AND AI.VENDOR_ID = APS.VENDOR_ID AND APSA.INVOICE_ID = AI.INVOICE_ID AND POV.VENDOR_ID = AI.VENDOR_ID AND POV.VENDOR_SITE_ID = AI.VENDOR_SITE_ID AND AI.TERMS_ID = ATL.TERM_ID AND AI.INVOICE_ID = AIPA.INVOICE_ID(+) AND AIPA.CHECK_ID = ACA.CHECK_ID(+) AND AP_INVOICES_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) NOT IN ('CANCELLED') AND AP_INVOICES_UTILITY_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE) NOT IN ('CANCELLED') AND AI.INVOICE_ID = AID.INVOICE_ID AND AI.INVOICE_ID = AILA.INVOICE_ID(+) AND GLCC.CODE_COMBINATION_ID = AID.DIST_CODE_COMBINATION_ID AND AID.INVOICE_LINE_NUMBER = AILA.LINE_NUMBER AND IEBA.EXT_BANK_ACCOUNT_ID(+) = AI.EXTERNAL_BANK_ACCOUNT_ID AND IEBA.BANK_ID = IEB.BANK_PARTY_ID(+) AND AI.INVOICE_ID = AILA.INVOICE_ID(+) AND AILA.PO_HEADER_ID = PHA.PO_HEADER_ID(+) AND AILA.RCV_TRANSACTION_ID = RT.TRANSACTION_ID(+) AND RT.SHIPMENT_HEADER_ID = RSH.SHIPMENT_HEADER_ID(+) GROUP BY AB.ATTRIBUTE1, HP.PARTY_NAME, AB.BATCH_ID, AI.ORG_ID, AB.BATCH_NAME, APSA.DUE_DATE, AI.INVOICE_CURRENCY_CODE, DECODE (AB.ATTRIBUTE2, NULL, HP.PARTY_NAME, AB.ATTRIBUTE2, AB.ATTRIBUTE2), AB.ATTRIBUTE3, FU.USER_NAME, APS.VAT_REGISTRATION_NUM, IEB.BANK_NAME, AI.INVOICE_AMOUNT, IEBA.BANK_ACCOUNT_NAME, IEBA.BANK_ACCOUNT_NUM, AI.INVOICE_ID, AI.INVOICE_NUM, AI.INVOICE_DATE, AI.GL_DATE, AI.EXCHANGE_RATE, AI.EXCHANGE_DATE, AI.EXCHANGE_RATE_TYPE, AI.INVOICE_CURRENCY_CODE, AI.SUPPLIER_TAX_INVOICE_NUMBER, AI.SUPPLIER_TAX_INVOICE_DATE, AI.ATTRIBUTE_CATEGORY, ACA.ATTRIBUTE3, TO_CHAR (AI.ATTRIBUTE3, '9,999,999,999,999.9999'), TO_CHAR (AI.ATTRIBUTE4, '999,999,999,999.9999'), POV.VENDOR_SITE_CODE, PHA.SEGMENT1, PHA.CREATION_DATE, RSH.RECEIPT_NUM, RT.TRANSACTION_DATE, AI.DESCRIPTION, ATL.DUE_DAYS, GLCC.SEGMENT1, GLCC.SEGMENT2, GLCC.SEGMENT3, GLCC.SEGMENT4, GLCC.SEGMENT5, GLCC.SEGMENT6, GLCC.SEGMENT7, AILA.ATTRIBUTE8, AI.PAYMENT_STATUS_FLAG, AP_INVOICES_PKG.GET_APPROVAL_STATUS ( AI.INVOICE_ID, AI.INVOICE_AMOUNT, AI.PAYMENT_STATUS_FLAG, AI.INVOICE_TYPE_LOOKUP_CODE)) WHERE APPROVAL_STATUS_GL NOT IN ('CANCELLED') AND (NVL (ACCOUNTED_DR, 0) <> 0 OR NVL (ACCOUNTED_CR, 0) <> 0) AND ORG_ID = 82 AND RFP_NO = 'RFP/CRM/20/09/000008'
true
f418c7e0525a00d5fff26de761671a2210d23d6d
SQL
bpitaud/appinfo
/Database/maindatabase.sql
UTF-8
7,066
3.28125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Hôte : localhost:8889 -- Généré le : mer. 23 jan. 2019 à 14:21 -- Version du serveur : 5.7.23 -- Version de PHP : 7.2.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `domisep` -- -- -------------------------------------------------------- -- -- Structure de la table `capteur` -- CREATE TABLE `capteur` ( `nom` varchar(20) NOT NULL, `capteurID` varchar(200) NOT NULL, `typ` enum('lumiere','camera','humidite','temperature') NOT NULL, `pieceID` varchar(200) NOT NULL, `etat` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `capteur` -- INSERT INTO `capteur` (`nom`, `capteurID`, `typ`, `pieceID`, `etat`) VALUES ('alarme entree', '468086431', 'camera', '5c38f2a15fe26', 1), ('Ampoule cuisine', '6798643', 'lumiere', '5c38f2a15fe26', 1), ('humidite', '9876534', 'humidite', '5c38f2a15fe26', 1), ('température', '9876543456', 'temperature', '5c38f2a15fe26', 1); -- -------------------------------------------------------- -- -- Structure de la table `controleur` -- CREATE TABLE `controleur` ( `controleurID` varchar(200) NOT NULL, `nom` varchar(20) NOT NULL, `typ` enum('chauffage') NOT NULL, `etat` int(6) NOT NULL, `pieceID` varchar(200) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `controleur` -- INSERT INTO `controleur` (`controleurID`, `nom`, `typ`, `etat`, `pieceID`) VALUES ('0987654', 'chauffage', 'chauffage', 1, '5c38f2a15fe26'); -- -------------------------------------------------------- -- -- Structure de la table `logement` -- CREATE TABLE `logement` ( `logementID` varchar(200) NOT NULL, `nom` varchar(100) NOT NULL, `adresse` varchar(100) NOT NULL, `codepostale` int(11) DEFAULT NULL, `surface` int(11) NOT NULL, `utilisateurID` varchar(200) NOT NULL, `pays` varchar(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `logement` -- INSERT INTO `logement` (`logementID`, `nom`, `adresse`, `codepostale`, `surface`, `utilisateurID`, `pays`) VALUES ('5c20fe562474c', 'Paris', '206 Avenue paul doumer', 35782, 60975, '2', 'france'), ('5c2f6d305292d', 'Meribel', '206 Avenue paul doumer', 35782, 6000, '4', 'france'), ('5c45f1b16b732', 'Rueil', 'le plateau', 35782, 4000, '2', 'france'), ('5c475360049b9', 'Sa Riera', 'le plateau', 35782, 4000, '2', 'france'), ('5c4764365dc2a', 'Mériblel', 'le plateau', 35782, 400, '2', 'france'), ('5c47644f324c3', 'zeuhozr', 'zierhizeor', 1887, 17899, '2', 'france'); -- -------------------------------------------------------- -- -- Structure de la table `piece` -- CREATE TABLE `piece` ( `pieceID` varchar(200) NOT NULL, `nom` varchar(20) NOT NULL, `surface` int(11) NOT NULL, `logementID` varchar(200) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `piece` -- INSERT INTO `piece` (`pieceID`, `nom`, `surface`, `logementID`) VALUES ('5c38f2a15fe26', 'salle à manger', 350, '5c20fe562474c'), ('5c3dfb5c5c57c', 'bureau', 15, '5c20fe562474c'), ('5c4224c79b504', 'salle de bain', 16, '5c20fe562474c'), ('5c432ba454a97', 'salle à manger', 15, '5c20fe562474c'); -- -------------------------------------------------------- -- -- Structure de la table `utilisateur` -- CREATE TABLE `utilisateur` ( `utilisateurID` varchar(200) NOT NULL, `nom` varchar(25) NOT NULL, `prenom` varchar(20) NOT NULL, `email` varchar(250) NOT NULL, `genre` varchar(15) NOT NULL, `naissance` varchar(200) DEFAULT NULL, `telephone` varchar(15) NOT NULL, `adresse` varchar(100) NOT NULL, `pays` varchar(11) NOT NULL, `codepostale` int(11) DEFAULT NULL, `mdp` varchar(200) NOT NULL, `administrateur` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `utilisateur` -- INSERT INTO `utilisateur` (`utilisateurID`, `nom`, `prenom`, `email`, `genre`, `naissance`, `telephone`, `adresse`, `pays`, `codepostale`, `mdp`, `administrateur`) VALUES ('13', 'Bruzeau', 'Haude', 'haudebruzeau@yahoo.fr', 'feminin', '12 mai 1997', '0663792528', '206 Avenue paul doumer', 'italie', 75016, '$2y$10$7CbOh9SJliGrSIpF3v5NjOWggUjd4Xy4cDypY5q.GRPWHQseeqtUK', 0), ('14', 'du Besset', 'Augustin', 'augustindubesset@sfr.fr', 'masculin', '12 mai 1997', '0662022527', 'le plateau', 'france', 35782, '$2y$10$SJlrJfNOUgCrenPZGbYd6OmUJt4kPHHaeVXVdikeJl7kFByBPrwf2', 0), ('2', 'Bruzeau', 'Camille', 'charlotte.bruzeau@yahoo.fr', 'masculin', '24/09/1997', '0663792527', '206 Avenue paul doumer', 'france', 36000, '$2y$10$f74hW2pBIbHEP/zkRfU.WuAJCTD5H3Du6.03avnYNMVxdAF/Buagm', 0), ('4', 'du Besset', 'Augustin', 'charlotte.bruzeau@gmail.com', 'feminin', '1998-08-23', '0662022527', '206 Avenue paul doumer', 'france', 92500, '$2y$10$Mo5qYhOBJ89QSb7HIWffu.75gcnTrWqJhwvZkcltW1CM.dYfS4wTG', 1), ('5c486f4213939', 'Berton', 'Léo', 'leoantoineberton@gmail.com', 'masculin', '16 juillet 1997', '0637462538', '206 Avenue paul doumer', 'italie', 78420, '$2y$10$suvSEV.ZD0L1lbmEUM9PKOZ.7YTNQTs1Uz9QExPN1JjPI6kmvSSWW', 0); -- -- Index pour les tables déchargées -- -- -- Index pour la table `capteur` -- ALTER TABLE `capteur` ADD PRIMARY KEY (`capteurID`), ADD KEY `pieceID` (`pieceID`); -- -- Index pour la table `controleur` -- ALTER TABLE `controleur` ADD PRIMARY KEY (`controleurID`), ADD KEY `pieceID` (`pieceID`); -- -- Index pour la table `logement` -- ALTER TABLE `logement` ADD PRIMARY KEY (`logementID`), ADD KEY `utilisateurID` (`utilisateurID`); -- -- Index pour la table `piece` -- ALTER TABLE `piece` ADD PRIMARY KEY (`pieceID`), ADD KEY `logementID` (`logementID`); -- -- Index pour la table `utilisateur` -- ALTER TABLE `utilisateur` ADD PRIMARY KEY (`utilisateurID`); -- -- Contraintes pour les tables déchargées -- -- -- Contraintes pour la table `capteur` -- ALTER TABLE `capteur` ADD CONSTRAINT `capteur_ibfk_1` FOREIGN KEY (`pieceID`) REFERENCES `piece` (`pieceID`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Contraintes pour la table `controleur` -- ALTER TABLE `controleur` ADD CONSTRAINT `controleur_ibfk_1` FOREIGN KEY (`pieceID`) REFERENCES `piece` (`pieceID`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Contraintes pour la table `logement` -- ALTER TABLE `logement` ADD CONSTRAINT `logement_ibfk_1` FOREIGN KEY (`utilisateurID`) REFERENCES `utilisateur` (`utilisateurID`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Contraintes pour la table `piece` -- ALTER TABLE `piece` ADD CONSTRAINT `piece_ibfk_1` FOREIGN KEY (`logementID`) REFERENCES `logement` (`logementID`) ON DELETE CASCADE ON UPDATE CASCADE; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
01bc45fd55ce0fea3b90a3643056e50ddf8f7eea
SQL
Oleg-Loginov-analyst/mybi-dbt-core
/models/staging/amocrm/stg_amo_leads_facts.sql
UTF-8
589
3.390625
3
[]
no_license
with source as ( select f.account_id , f.clientids_id , f.users_id , f.leads_id , f.contacts_id , f.companies_id , f.unsorteds_id , created.dt as created_dt , closed.dt as closed_dt , f.price from {{ source('amocrm', 'leads_facts') }} as f left join {{ ref('stg_general_dates') }} as created on created.id = f.created_id left join {{ ref('stg_general_dates') }} as closed on closed.id = f.closed_id {{ filter_rows( account_id=var('account_id_amocrm'), last_number_of_days=false, ts_field=none ) }} ) select * from source
true
2c0cd46137ccbfda4d2129fac6b25ade64ab44c7
SQL
NoraCarey/Leetcode-SQL
/SQL/1501. Countries You Can Safely Invest In/mysql_group_by_having.sql
UTF-8
235
3.65625
4
[]
no_license
SELECT DISTINCT c.name AS country FROM Person p JOIN Calls l ON caller_id = id OR id = callee_id JOIN Country c ON LEFT(phone_number, 3) = country_code GROUP BY country_code HAVING AVG(duration) > (SELECT AVG(duration) FROM Calls)
true
3fa2aa357ba5cd0748468a541e5f3c3d6f00cf1b
SQL
RBancal/OClock-Memory
/sql/db.sql
UTF-8
412
2.828125
3
[]
no_license
CREATE DATABASE IF NOT EXISTS `memory` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE USER 'oclock'@'localhost' IDENTIFIED VIA mysql_native_password USING '***'; GRANT USAGE ON *.* TO 'oclock'@'localhost' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; GRANT ALL PRIVILEGES ON `memory`.* TO 'oclock'@'localhost' WITH GRANT OPTION;
true
3cf51108cdddb7781fffa39adbb81461b7612705
SQL
unisung/database
/och01/build/classes/sql/ch14_02.sql
UTF-8
2,134
4.09375
4
[]
no_license
--ex1. if문을 사용하여 king사원의 부서번호를 얻어와서 부서번호에 따른 부서명 출력 declare--선언부 v_dname department.dname%type; v_dno department.dno%type; begin--실행부 select dno into v_dno from employee where ename =upper('king'); if v_dno=10 then v_dname :='ACCOUNT'; elsif v_dno=20 then v_dname :='RESEARCH'; elsif v_dno=30 then v_dname := 'SALES'; elsif v_dno=40 then v_dname := 'OPERATION'; end if; dbms_output.put_line('king의 부서번호는 '||v_dno||' ' ||'부서명은'||v_dname); end; --basic loop 1~10사이의 자연수 합 구하기 declare--선언부 tot number :=0; n number:=1; begin--실행부 loop --basic loop tot :=tot+n; n:=n+1; if n>10 then--loop 빠져나가는 조건 exit;--loop빠져나가는 명령문; end if; end loop; dbms_output.put_line('총합:'||tot); end; --ex3. for loop 1..10 합 declare--선언부 tot number :=0; begin--실행부 for i in 1..10 loop --for 변수 in 하한..상한 loop tot := tot+i; end loop; dbms_output.put_line('총합'||tot); end; --ex4. while loop 1 ~10 자연수 합 declare n number:=1; tot number:=0; begin while n<=10 loop tot :=tot+n; n:=n+1; end loop; dbms_output.put_line('총합'||tot); end; declare n number:=1; tot number:=0; begin while n<=10 loop if mod(n,2)=0 then--mod(피젯수,제수) 나머지 tot :=tot+n; end if; n:=n+1; end loop; dbms_output.put_line('총합'||tot); end; --ex5. 사원 테이블 커미션이 null이 아닌 상태의 사원번호,이름,급여를 기준 오름차순 정렬 결과출력 select eno,ename,salary from employee order by eno; declare v_emp employee%rowtype; --1.커서 생성 cursor c1 is select * from employee where commission is not null; begin dbms_output.put_line('사번 이름 급여'); dbms_output.put_line('--------------'); open c1;--2.커서 오픈 loop fetch c1 into v_emp;--3.fetch exit when c1%notfound; dbms_output.put_line(v_emp.eno||' '||v_emp.ename||' '||v_emp.salary); end loop; close c1;--4.커서 닫기 end;
true
32ee06727b5629b4868d29036294b6b2fabfb4ce
SQL
min-87/tasks-advanced
/SQL/DDL-DML/9_schema.sql
UTF-8
368
2.75
3
[]
no_license
--Выполните в psql следующие запросы: -- Создание схемы custom. -- Создание последовательности serial в новой схеме. DROP SEQUENCE IF EXISTS custom.serial; DROP SCHEMA IF EXISTS custom; -- BEGIN (write your solution here) CREATE SCHEMA custom; CREATE SEQUENCE custom.serial; -- END
true
084c64f28cb90eeb3cfb43925df1a49c75cb5d30
SQL
kushdeepwalia/Expense_Manager
/Database/expense_clients.sql
UTF-8
1,632
3.03125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Dec 02, 2020 at 03:46 PM -- Server version: 10.4.13-MariaDB -- PHP Version: 7.4.8 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: `expense_clients` -- -- -------------------------------------------------------- -- -- Table structure for table `all_users` -- CREATE TABLE `all_users` ( `S. No.` int(11) NOT NULL, `Username` varchar(50) NOT NULL, `Password` varchar(10) NOT NULL, `Email` text NOT NULL, `Wallet Name` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `all_users` -- INSERT INTO `all_users` (`S. No.`, `Username`, `Password`, `Email`, `Wallet Name`) VALUES (2, 'kushdeep', '12345678', 'skushdeep5@gmail.com', 'kush'), (3, 'dkarya', '123456', 'dkarya@gmail.com', 'JanDhan Khata'); -- -- Indexes for dumped tables -- -- -- Indexes for table `all_users` -- ALTER TABLE `all_users` ADD PRIMARY KEY (`S. No.`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `all_users` -- ALTER TABLE `all_users` MODIFY `S. No.` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; 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
077d3aa874ba928a24ecfa3820e96579bcbb4996
SQL
moon70717/test
/iot_db/171214.sql
UTF-8
6,940
3.953125
4
[]
no_license
/* USE iot2; CREATE TABLE user_info( userno int auto_increment primary key, username varchar(100) not null, userage int(5) not null, userid varchar(100) not null, userpwd varchar(100) not null ); INSERT INTO user_info VALUES(1,'홍길동',20,'testid','testpw'); INSERT INTO user_info(username,userage,userid,userpwd) VALUES('홍길동',20,'testid','testpw'); INSERT INTO user_info(username,userage,userid,userpwd) VALUES('김길동',22,'tset','test'); INSERT INTO user_info(username,userage,userid,userpwd) VALUES('김길김',22,'tset3','test3'); SELECT * FROM user_info WHERE userno NOT IN(2,3); SELECT * FROM user_info WHERE username NOT LIKE '김%'; UPDATE USER_INFO SET USERNAME='김화동' , USERAGE=30 WHERE USERNO=5; SELECT * FROM USER_INFO; DELETE FROM USER_INFO WHERE USERNAME='홍길동'; SELECT * FROM USER_INFO WHERE USERNO=(SELECT MIN(USERNO) FROM USER_INFO WHERE USERNAME='김길김'); SELECT SUM(USERAGE),AVG(USERAGE), COUNT(USERAGE) FROM USER_INFO; DROP TABLE USER_INFO; insert into user_info(username,userage,userid,userpwd) values('홍길동',30,'hong','hong'), ('흙길동',10,'black','black'), ('백길동',40,'white','white'), ('청길동',52,'blue','blue'); #얍야뱌얍야얌ㄴ림ㄴ른ㅁㄹㄴㅁㄹㄴㅁㄹㄴㅁㄹㄴㅁㄹㄴㅁㄹㄴㅁ SELECT * FROM USER_INFO WHERE USERAGE<=30 AND USERNAME LIKE '흙%'; SELECT * FROM USER_INFO WHERE USERAGE=52 OR USERID='hong'; SELECT * FROM USER_INFO WHERE USERAGE>=20 OR USERAGE<=30; /* userage가 가장 작은 사람이거나 제일 많은사람을 검색해주세요 */ /* SELECT * FROM USER_INFO WHERE USERAGE IN ((SELECT MIN(USERAGE) FROM USER_INFO), (SELECT MAX(USERAGE) FROM USER_INFO)); SELECT * FROM USER_INFO h1, (SELECT MIN(USERAGE) B FROM USER_INFO)A WHERE H1.USERAGE=A.B; CREATE TABLE class_info( cino int auto_increment primary key, ciname varchar(100) not null, cidesc varchar(500) ); INSERT INTO class_info(ciname, cidesc) VALUES ('포토일러','포토샵과 일러스트반'); ALTER TABLE USER_INFO ADD COLUMN cino INT NOT NULL DEFAULT 1; SELECT USER.USERNO AS NO, USER.USERNAME AS NAME FROM USER_INFO AS USER; SELECT * FROM USER_INFO AS USER, (SELECT * FROM CLASS_INFO) AS CLASS; user_infouser_info SELECT UI.USERNO, UI.USERNAME, CI.CINO, CI.CINAME, CI.CIDESC FROM USER_INFO UI, CLASS_INFO CI WHERE UI.CINO=CI.CINO; UPDATE CLASS_INFO SET CIDESC='IOT CLASS' WHERE CINO=1; SELECT * FROM CLASS_INFO; UPDATE USER_INFO SET CINO=2 WHERE USERNO>2; SELECT CI.CINO, CI.CINAME, COUNT(*) FROM USER_INFO UI, CLASS_INFO CI WHERE UI.CINO=CI.CINO GROUP BY CI.CINO,CI.CINAME; SELECT CI.CINO, CI.CINAME ,(SELECT COUNT(*) FROM USER_INFO UI WHERE UI.CINO=CI.CINO)AS COUNT FROM CLASS_INFO CI GROUP BY CI.CINO, CI.CINAME; INSERT INTO class_info(ciname, cidesc) VALUES ('포토일러','포토샵과 일러스트반'); INSERT INTO USER_INFO(username,userage,userid,userpwd,CINO) VALUES('오길동',20,'OH','OH',(SELECT CI.CINO FROM CLASS_INFO CI WHERE CI.CINAME='포토일러')); SELECT UI.* FROM USER_INFO UI WHERE UI.CINO=(SELECT CI2.CINO FROM CLASS_INFO CI2 WHERE CI2.CINAME='IOT'); SELECT UI.*, CI.* FROM USER_INFO UI, CLASS_INFO CI WHERE UI.USERAGE>=30 AND CI.CIDESC LIKE '%반%' AND CI.CINO=UI.CINO; SELECT UI.*, CI.* FROM USER_INFO UI, CLASS_INFO CI WHERE CI.CINAME LIKE '%퍼블%' AND CI.CINO=UI.CINO; UI.CINO IN((SELECT CI.CINO FROM CLASS_INFO WHERE CI.CINAME LIKE ('%퍼블%'))); SELECT UI.*,CI.* FROM USER_INFO UI, CLASS_INFO CI WHERE UI.CINO=CI.CINO; SELECT * FROM USER_INFO; INSERT INTO USER_INFO(USERNAME, USERAGE, USERID, USERPWD, CINO) VALUES('TEST',20,'TEST','TEST',5); DELETE FROM CLASS_INFO WHERE CINO=4; DROP TABLE USER_INFO, CLASS_INFO; *//* Drop Tables */ DROP TABLE IF EXISTS user_info; DROP TABLE IF EXISTS class_info; /* Create Tables */ -- 반 정보 CREATE TABLE class_info ( cino int unsigned NOT NULL AUTO_INCREMENT COMMENT '반 번호', ciname varchar(100) NOT NULL COMMENT '반 이름', cidesc varchar(100) COMMENT '반 설명', PRIMARY KEY (cino), UNIQUE (ciname) ) COMMENT = '반 정보'; -- 유저정보테이블 CREATE TABLE user_info ( urno int unsigned NOT NULL AUTO_INCREMENT COMMENT '유저번호', urname varchar(100) NOT NULL COMMENT '유저이름', urage tinyint unsigned NOT NULL COMMENT '유저나이', urid varchar(100) NOT NULL COMMENT '유저아이디', urpwd varchar(100) NOT NULL COMMENT '유저비밀번호', cino int unsigned NOT NULL COMMENT '반 번호', PRIMARY KEY (urno), UNIQUE (urid) ) COMMENT = '유저정보테이블'; /* Create Foreign Keys */ ALTER TABLE user_info ADD CONSTRAINT FK_class_info_cino FOREIGN KEY (cino) REFERENCES class_info (cino) ON UPDATE RESTRICT ON DELETE RESTRICT ; /* Drop Tables */ DROP TABLE IF EXISTS user_info; DROP TABLE IF EXISTS class_info; /* Create Tables */ -- 반 정보 CREATE TABLE class_info ( cino int unsigned NOT NULL AUTO_INCREMENT COMMENT '반 번호', ciname varchar(100) NOT NULL COMMENT '반 이름', cidesc varchar(100) COMMENT '반 설명', PRIMARY KEY (cino), UNIQUE (ciname) ) COMMENT = '반 정보'; -- 유저정보테이블 CREATE TABLE user_info ( urno int unsigned NOT NULL AUTO_INCREMENT COMMENT '유저번호', urname varchar(100) NOT NULL COMMENT '유저이름', urage tinyint unsigned NOT NULL COMMENT '유저나이', urid varchar(100) NOT NULL COMMENT '유저아이디', urpwd varchar(100) NOT NULL COMMENT '유저비밀번호', cino int unsigned NOT NULL COMMENT '반 번호', PRIMARY KEY (urno), UNIQUE (urid) ) COMMENT = '유저정보테이블'; /* Create Foreign Keys */ ALTER TABLE user_info ADD CONSTRAINT FK_class_info_cino FOREIGN KEY (cino) REFERENCES class_info (cino) ON UPDATE RESTRICT ON DELETE RESTRICT ; SELECT * FROM USER_INFOclass_infoclass_info; INSERT INTO CLASS_INFO (CINAME,CIDESC) VALUES('IOT','IOT반'), ('3D','3D함'), ('정보보안','보안'); SELECT * FROM USER_INFO; INSERT INTO USER_INFO(URNAME,URAGE,URID,URPWD,CINO) VALUES('홍길동',30,'RED','RED',1), ('금길동',20,'GOLD','GOLD',2), ('백길동',10,'WHITE','WHITE',3); SELECT * FROM USER_INFO UI, CLASS_INFO CI WHERE UI.CINO=CI.CINO; #AUTOCOMMIT 관련 설정 SELECT @@AUTOCOMMIT; SET @@AUTOCOMMIT=0; INSERT INTO USER_INFO(URNAME,URAGE,URID,URPWD,CINO) VALUES('청길동',30,'BLUE3','BLUE',1); SELECT * FROM USER_INFO; ROLLBACK; COMMIT; ALTER TABLE USER_INFO DROP COLUMN uiregdate; ALTER TABLE USER_INFO ADD COLUMN uiregdate DATETIME DEFAULT now(); SELECT UINO, CONCAT(UINAME,UIAGE) UINAMENAGE, UIID FROM USER_INFO; SELECT UI.*, CI.* FROM USER_INFO UI, CLASS_INFO CI WHERE UI.CINO=CI.CINO GROUP BY CI.CINAME, CI.CIDESC;
true
33c36b9360de8f93eadd7d7de2d2249e26ca9e4f
SQL
BazilGod/Database-3-course
/8.sql
UTF-8
494
2.90625
3
[]
no_license
SELECT a.name, a.value FROM v$parameter a ORDER BY a.name; connect BAZ/qwerty@localhost:1521/pdb_a ; SELECT TABLESPACE_NAME FROM DBA_TABLESPACES; SELECT USERNAME FROM DBA_USERS; SELECR ROLE FROM DBA_ROLES; SELECT * FROM USER_SEGMENTS ; SELECT table_name FROM user_tables; CREATE VIEW BAZ_VIEW3 AS SELECT count(*) kolichestvosegments, sum(EXTENTS) kolichestvoextents,SUM(BLOCKS) kolichestvobloks,SUM(BYTES) vesblocksvbaits FROM USER_SEGMENTS ; SELECT * FROM BAZ_VIEW3; drop VIEW BAZ_VIEW3;
true
65fcc3385099f66b7c69788fb5ef0e4fb7787642
SQL
Izar111/Viva-Pro.
/DB/CREATE_function.sql
UTF-8
4,398
3.640625
4
[ "MIT" ]
permissive
-- Return user input sentence with named entities from SENTENCE table ----------------------------------------------------------------------------------- DROP FUNCTION IF EXISTS F_PrintOriginSentence; DELIMITER // CREATE FUNCTION `F_PrintOriginSentence`(in_uid VARCHAR(30), in_number INT ) RETURNS VARCHAR(512) BEGIN DECLARE out_result VARCHAR(512); DECLARE i INT; DECLARE max_id INT; DECLARE temp_word VARCHAR(512); DECLARE temp_before VARCHAR(512); DECLARE temp_inter VARCHAR(512); DECLARE temp_after VARCHAR(512); DECLARE temp_spos INT; DECLARE temp_word_length INT; DECLARE temp_tag_length INT; DECLARE temp_tag VARCHAR(4); DECLARE s_num INT; SET s_num = 0; SET i = 0; SELECT MAX(Wid) INTO max_id FROM WORD WHERE Uid = in_uid AND Snumber = in_number; SET out_result = ""; WHILE i <= max_id DO SELECT Wtag INTO temp_tag FROM WORD WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; SELECT Wform INTO temp_word FROM WORD WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; IF(temp_tag <> "O") THEN SELECT Wspos, Wepos - Wspos, CHAR_LENGTH(Wform) INTO temp_spos, temp_tag_length, temp_word_length FROM WORD WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; SET temp_before = LEFT(temp_word, temp_spos - s_num); SET temp_inter = SUBSTRING(temp_word, temp_spos - s_num + 1, temp_tag_length); SET temp_after = RIGHT(temp_word, temp_word_length - temp_tag_length); SET temp_word = CONCAT(temp_before, "[", temp_inter, ":", temp_tag, "]", temp_after); END IF; SET out_result = CONCAT(out_result, " ", temp_word); SELECT s_num + CHAR_LENGTH(Wform) + 1 INTO s_num FROM WORD WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; SET i = i + 1; END WHILE; RETURN out_result; END // DELIMITER ; -- Return user reported sentence with named entities from SENTENCE and REPORT table ------------------------------------------------------------------------------------------------------ DROP FUNCTION IF EXISTS F_PrintReportSentence; DELIMITER // CREATE FUNCTION `F_PrintReportSentence`(in_uid VARCHAR(30), in_number INT) RETURNS VARCHAR(512) BEGIN DECLARE out_result VARCHAR(512); DECLARE i INT; DECLARE max_id INT; DECLARE temp_word VARCHAR(512); DECLARE temp_before VARCHAR(512); DECLARE temp_inter VARCHAR(512); DECLARE temp_after VARCHAR(512); DECLARE temp_spos INT; DECLARE temp_word_length INT; DECLARE temp_tag_length INT; DECLARE temp_tag VARCHAR(4); DECLARE s_num INT; DECLARE report_id INT; SET s_num = 0; SET i = 0; SELECT MAX(Wid) INTO max_id FROM WORD WHERE Uid = in_uid AND Snumber = in_number; SELECT Wid INTO report_id FROM REPORT WHERE Uid = in_uid AND Snumber = in_number AND Rstate = 0; SET out_result = ""; WHILE i <= max_id DO SELECT Wform INTO temp_word FROM WORD WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; IF(i = report_id) THEN SELECT Rtag INTO temp_tag FROM REPORT WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; ELSE SELECT Wtag INTO temp_tag FROM WORD WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; END IF; IF(temp_tag <> "O") THEN IF(i = report_id) THEN SELECT Rspos, Repos - Rspos, CHAR_LENGTH(Wform) INTO temp_spos, temp_tag_length, temp_word_length FROM WORD NATURAL JOIN REPORT WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; ELSE SELECT Wspos, Wepos - Wspos, CHAR_LENGTH(Wform) INTO temp_spos, temp_tag_length, temp_word_length FROM WORD WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; END IF; SET temp_before = LEFT(temp_word, temp_spos - s_num); SET temp_inter = SUBSTRING(temp_word, temp_spos - s_num + 1, temp_tag_length); SET temp_after = RIGHT(temp_word, temp_word_length - temp_tag_length); SET temp_word = CONCAT(temp_before, "[", temp_inter, ":", temp_tag, "]", temp_after); END IF; SET out_result = CONCAT(out_result, " ", temp_word); SELECT s_num + CHAR_LENGTH(Wform) + 1 INTO s_num FROM WORD WHERE Uid = in_uid AND Snumber = in_number AND Wid = i; SET i = i + 1; END WHILE; RETURN out_result; END // DELIMITER ;
true
93e0bfa63abd641b3fc50e7a811206a1c004e514
SQL
fabiomigliorini/MGdb
/SQLs/NFe Terceiro - Ajusta Cadastro Produto.sql
UTF-8
1,698
3.15625
3
[]
no_license
/* select * from tblmarca where marca ilike '%queen%' update tblproduto set codmarca = 30000141 where codmarca in ( 30010280 ,10000430 ,10000431 ) "Mc Queen" "Queen" select produto, replace(produto, 'Queen', 'Mc Queen') from tblproduto where produto ilike '%Queen%' and produto not ilike '%mc Queen%' and codmarca = 30000141 update tblproduto set produto = replace(produto, 'Queen', 'Mc Queen') where produto ilike '%Queen%' and produto not ilike '%mc Queen%' and codmarca = 30000141 select produto, replace(produto, 'Caderno Tilibra Brochura 1/4 96fls', 'Caderno Tilibra 1/4 96fls Cd Cost Broch') from tblproduto where produto ilike 'Caderno Tilibra Brochura 1/4 96fls Cd Cost%' update tblproduto set produto = replace(produto, 'Caderno Tilibra Cost Cd 1/4 96fls', 'Caderno Tilibra 1/4 96fls Cd Cost') where produto ilike 'Caderno Tilibra Cost Cd 1/4 96fls%' update tblnfeterceiroitem set margem = 55 where codnfeterceiro = 3688 */ /* select * from tblnotafiscalprodutobarra nfpb where nfpb.codnotafiscal in ( select nf.codnotafiscal from tblnotafiscal nf where nf.nfeautorizacao is null and nf.nfecancelamento is null and nf.nfeinutilizacao is null and nf.emissao >= '2015-12-01 00:00:00.0' ) and nfpb.codcfop = 5102 and nfpb.csosn = '500' update tblnotafiscalprodutobarra nfpb set csosn = '900' where nfpb.codnotafiscal in ( select nf.codnotafiscal from tblnotafiscal nf where nf.nfeautorizacao is null and nf.nfecancelamento is null and nf.nfeinutilizacao is null and nf.emissao >= '2015-12-01 00:00:00.0' ) and nfpb.codcfop = 5102 and nfpb.csosn = '500' */ /* update tblproduto set produto = replace(produto, '20X1', '20x1') where produto ilike '%20X1%' */
true
2e54e667a431f2bdb3fc67b27dac21216709bcf8
SQL
dvkom/skillbox-learning
/11/5/Количество сотрудников по отделам.sql
UTF-8
110
3.5
4
[]
no_license
SELECT d.name, COUNT(e.id) FROM learn.employee e JOIN learn.department d ON d.id=e.department_id GROUP BY d.id
true
e6cbf4566addad13f87dfd00132c2771769dd9da
SQL
brynschulha/LightBnb
/seeds/01_seeds.sql
UTF-8
2,746
2.6875
3
[]
no_license
INSERT INTO users (id, name, email, password) VALUES (1, 'Joe', 'joe@yahoo.com', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'), (2, 'Bob', 'bob@gmail.com', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'), (3, 'John', 'john@hotmail.com', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'); INSERT INTO properties (id, owner_id, title, description, thumbnail_photo_url, cover_photo_url, cost_per_night, parking_spaces, number_of_bathrooms, number_of_bedrooms, country, street, city, province, post_code, active) VALUES (1, '2', 'McDavid Manor', 'description', 'https://i.cbc.ca/1.4199693.1499794257!/fileImage/httpImage/edmonton-mcdavid.jpg', 'https://edifyedmonton.com/wp-content/uploads/McDavid_kitchen-1200x675.jpg', 1000, 2, 5, 8, 'Canada', '123 Oilers Street', 'Edmonton', 'Alberta', 'GO-OIL1', true ), (2, '3', 'LoserVille', 'description', 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTx5r0KrLByJZ-tX2B_dKzYjlkdsNl_DUNklg&usqp=CAU', 'https://cdn.ultiworld.com/wordpress/wp-content/uploads/2018/05/garbage-dump.jpg', 1, 0, 0, 0, 'Canada', 'Dump', 'Calgary', 'Alberta', 'FLMS-SCK', true ), (3, '1', 'Costly Condo', 'description', 'https://cdn.home-designing.com/wp-content/uploads/2020/01/studio-apartment-design.jpg', 'https://i.insider.com/55f96fa0dd08952f3a8b4709?width=1100&format=jpeg&auto=webp', 1000000, 0, 1, 0, 'Canada', 'ExpensiveRentStreet', 'Vancouver', 'British Columbia', 'V$$ $$$', false ); INSERT INTO reservations (id, start_date, end_date, property_id, guest_id) VALUES (1, '2018-04-01', '2018-04-04', 1, 2), (2, '2019-05-02', '2019-05-03', 1, 3), (3, '2020-03-16', '2020-10-14', 3, 1); INSERT INTO property_reviews (id, guest_id, property_id, reservation_id, rating, message) VALUES (1, 2, 1, 1, 5, 'message'), (2, 3, 1, 2, 4, 'message'), (3, 1, 3, 3, 2, 'message');
true
62666bd92c2f00ce21d1254c0a902e3f32fb8d8e
SQL
Hadden-Industries/oracle
/USERS/RD/PROCEDURES/TOUCH.sql
UTF-8
2,888
3.875
4
[ "MIT", "Apache-2.0" ]
permissive
CREATE OR REPLACE PROCEDURE TOUCH ( gTable_Name IN TABLELOOKUP.Name%TYPE, gDateTimeReference IN DATE DEFAULT SYSDATE_UTC ) AS c SYS_REFCURSOR; nCount INTEGER := 0; vTable_Name TABLELOOKUP.Name%TYPE := ORACLE_NAME(gTable_Name); BEGIN SELECT COUNT(*) INTO nCount FROM TABLELOOKUP WHERE Name = vTable_Name; IF nCount > 0 THEN UPDATE TABLELOOKUP SET DateTimeUpdated = gDateTimeReference WHERE Name = vTable_Name; UPDATE TABLELOOKUP SET DateTimeUpdated = SYSDATE_UTC WHERE Name = 'TABLELOOKUP'; IF vTable_Name != 'S_TOWNNAME' THEN --EXECUTE IMMEDIATE does not seem to handle hints OPEN c FOR 'SELECT /*+ FULL(' || vTable_Name || ') */ COUNT(*) AS CountX FROM "' || vTable_Name || '"'; LOOP FETCH c INTO nCount; EXIT WHEN c%NOTFOUND; END LOOP; CLOSE c; ELSE SELECT /*+ FULL(S_TOWNNAME) */ COUNT(*) AS CountX INTO nCount FROM S_TOWNNAME; END IF; MERGE INTO TABLECOUNT X USING ( SELECT vTable_Name AS TableLookup_Name, gDateTimeReference AS DateTimeX, nCount AS CountX FROM DUAL ) Y ON (X.TableLookup_Name = Y.TableLookup_Name AND X.DateTimeX = Y.DateTimeX) WHEN NOT MATCHED THEN INSERT ( TABLELOOKUP_NAME, DATETIMEX, COUNTX ) VALUES ( Y.TableLookup_Name, Y.DateTimeX, Y.CountX ) WHEN MATCHED THEN UPDATE SET X.CountX = Y.CountX; ELSE DBMS_OUTPUT.Put_Line(vTable_Name || ' is not in TABLELOOKUP'); END IF; END; / /* --test SET SERVEROUTPUT ON; BEGIN TOUCH ( 'COMPANYREGISTER'/*, CAST ( SYS_EXTRACT_UTC ( FROM_TZ ( CAST ( TO_DATE('2015-01-09T23:22:06', 'YYYY-MM-DD"T"HH24:MI:SS') AS TIMESTAMP ), 'Europe/London' ) ) AS DATE )*//* ); COMMIT; END; / --All table counts SET SERVEROUTPUT ON; BEGIN FOR C IN ( SELECT Name AS TableLookup_Name FROM TABLELOOKUP WHERE (Comments != 'Reserved' OR Comments IS NULL) ORDER BY ID ) LOOP TOUCH(C.TableLookup_Name); END LOOP; COMMIT; END; / */
true
7354c701143467d668fd50c171d4100360362d50
SQL
SoraNaiShiroNai/128.1-final
/128_1v2.sql
UTF-8
7,410
3.1875
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: May 02, 2019 at 06:27 AM -- Server version: 10.1.38-MariaDB -- PHP Version: 7.3.4 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: `128.1v2` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `id` int(10) UNSIGNED NOT NULL, `username` varchar(300) COLLATE utf8mb4_bin DEFAULT NULL, `user_password` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL, `full_name` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; -- -------------------------------------------------------- -- -- Table structure for table `applicants` -- CREATE TABLE `applicants` ( `id` int(10) UNSIGNED NOT NULL, `first_name` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL, `last_name` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL, `middle_initial` varchar(2) COLLATE utf8mb4_bin DEFAULT NULL, `sex` enum('M','F') COLLATE utf8mb4_bin DEFAULT NULL, `current_address` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL, `place_of_birth` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL, `birthdate` date DEFAULT NULL, `phone_number` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL, `email` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL, `linkedin_profile` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL, `educational_attainment` enum('College','Vocational','Highschool','Elementary') COLLATE utf8mb4_bin DEFAULT NULL, `civil_status` enum('S','M') COLLATE utf8mb4_bin DEFAULT NULL, `nationality` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL, `SSN` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL, `target_position` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL, `birth_certificate_id` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL, `user_password` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL, `skills_csv` varchar(6000) COLLATE utf8mb4_bin DEFAULT NULL, `job_history_csv` mediumtext COLLATE utf8mb4_bin, `approved` tinyint(1) DEFAULT '0', `do_not_show` tinyint(1) DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; -- -------------------------------------------------------- -- -- Table structure for table `employee` -- CREATE TABLE `employee` ( `id` int(10) UNSIGNED NOT NULL, `first_name` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL, `last_name` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL, `middle_initial` varchar(2) COLLATE utf8mb4_bin DEFAULT NULL, `sex` enum('M','F') COLLATE utf8mb4_bin DEFAULT NULL, `current_address` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL, `place_of_birth` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL, `birthdate` date DEFAULT NULL, `phone_number` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL, `email` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL, `linkedin_profile` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL, `educational_attainment` enum('College','Vocational','Highschool','Elementary') COLLATE utf8mb4_bin DEFAULT NULL, `civil_status` enum('S','M') COLLATE utf8mb4_bin DEFAULT NULL, `nationality` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL, `SSN` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL, `target_position` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL, `birth_certificate_id` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL, `employment_date` datetime DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; -- -------------------------------------------------------- -- -- Table structure for table `employee_deps` -- CREATE TABLE `employee_deps` ( `id` int(10) UNSIGNED NOT NULL, `employee_id` int(10) UNSIGNED NOT NULL, `dep_name` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL, `dep_relation` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; -- -------------------------------------------------------- -- -- Table structure for table `employee_job_history` -- CREATE TABLE `employee_job_history` ( `id` int(10) UNSIGNED NOT NULL, `employee_id` int(10) UNSIGNED NOT NULL, `job_name` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL, `job_desc` varchar(300) COLLATE utf8mb4_bin DEFAULT NULL, `year_started` int(11) DEFAULT NULL, `year_ended` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; -- -------------------------------------------------------- -- -- Table structure for table `employee_skills` -- CREATE TABLE `employee_skills` ( `id` int(10) UNSIGNED NOT NULL, `employee_id` int(10) UNSIGNED NOT NULL, `skill` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`); -- -- Indexes for table `applicants` -- ALTER TABLE `applicants` ADD PRIMARY KEY (`id`); -- -- Indexes for table `employee` -- ALTER TABLE `employee` ADD PRIMARY KEY (`id`); -- -- Indexes for table `employee_deps` -- ALTER TABLE `employee_deps` ADD PRIMARY KEY (`id`), ADD KEY `employee_id` (`employee_id`); -- -- Indexes for table `employee_job_history` -- ALTER TABLE `employee_job_history` ADD PRIMARY KEY (`id`), ADD KEY `employee_id` (`employee_id`); -- -- Indexes for table `employee_skills` -- ALTER TABLE `employee_skills` ADD PRIMARY KEY (`id`), ADD KEY `employee_id` (`employee_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `applicants` -- ALTER TABLE `applicants` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `employee` -- ALTER TABLE `employee` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `employee_deps` -- ALTER TABLE `employee_deps` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `employee_job_history` -- ALTER TABLE `employee_job_history` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `employee_skills` -- ALTER TABLE `employee_skills` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- Constraints for dumped tables -- -- -- Constraints for table `employee_deps` -- ALTER TABLE `employee_deps` ADD CONSTRAINT `employee_deps_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`id`); -- -- Constraints for table `employee_job_history` -- ALTER TABLE `employee_job_history` ADD CONSTRAINT `employee_job_history_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`id`); -- -- Constraints for table `employee_skills` -- ALTER TABLE `employee_skills` ADD CONSTRAINT `employee_skills_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
208d6f1e0543f83afadf2a9ee6047ab084f3563e
SQL
vekselman/Data_analysing
/Microsoft.DAT201x.tsql.DONE!/tsqlModule5.sql
UTF-8
2,571
4.375
4
[]
no_license
--Challenge 1: Retrieve Product Information --1.Retrieve the name and approximate weight of each product SELECT CONCAT(sp.ProductID, ' ' + UPPER(sp.Name)) as ProductIDName, ROUND(sp.Weight,-1) as ApproxWeight FROM SalesLT.Product as sp ORDER BY ApproxWeight DESC; --2.Retrieve the year and month in which products were first sold SELECT CONCAT(sp.ProductID, ' ' + UPPER(sp.Name)) as ProductIDName, ROUND(sp.Weight,-1) as ApproxWeight, YEAR(sp.SellStartDate) as SellStartYear, DATENAME(MONTH,sp.SellStartDate) as SellStartMonth FROM SalesLT.Product as sp ORDER BY ApproxWeight DESC; --3.Extract product types from product numbers SELECT CONCAT(sp.ProductID, ' ' + UPPER(sp.Name)) as ProductIDName, ROUND(sp.Weight,-1) as ApproxWeight, YEAR(sp.SellStartDate) as SellStartYear, DATENAME(MONTH,sp.SellStartDate) as SellStartMonth, LEFT(sp.ProductNumber,2) as ProductType FROM SalesLT.Product as sp ORDER BY ApproxWeight DESC; --4.Retrieve only products with a numeric size SELECT CONCAT(sp.ProductID, ' ' + UPPER(sp.Name)) as ProductIDName, ROUND(sp.Weight,-1) as ApproxWeight, YEAR(sp.SellStartDate) as SellStartYear, DATENAME(MONTH,sp.SellStartDate) as SellStartMonth, LEFT(sp.ProductNumber,2) as ProductType, sp.ProductNumber FROM SalesLT.Product as sp WHERE ISNUMERIC(SUBSTRING(ProductNumber,LEN(ProductNumber) - CHARINDEX('-',REVERSE(RIGHT(ProductNumber,3)))+2,2)) = 1 ORDER BY ApproxWeight DESC; --Challenge 2: Rank Customers by Revenue --1.Retrieve total sales by product SELECT sc.CompanyName, RANK() OVER(ORDER BY soh.TotalDue DESC) as Ranking FROM SalesLT.SalesOrderHeader as soh JOIN SalesLT.Customer as sc ON soh.CustomerID = sc.CustomerID ORDER BY soh.TotalDue DESC; --Challenge 3: Aggregate Product Sales --1.Retrieve total sales by product SELECT sp.Name, SUM(ISNULL(ssod.LineTotal,0.00)) as TotalSum FROM SalesLT.Product as sp JOIN SalesLT.SalesOrderDetail as ssod ON sp.ProductID = ssod.ProductID GROUP BY sp.Name; --2.Filter the product sales list to include only products that cost over $1,000 SELECT sp.Name, SUM(ISNULL(ssod.LineTotal,0.00)) as TotalSum FROM SalesLT.Product as sp JOIN SalesLT.SalesOrderDetail as ssod ON sp.ProductID = ssod.ProductID WHERE ssod.UnitPrice > 1000 GROUP BY sp.Name ORDER BY TotalSum; --3.Filter the product sales groups to include only total sales over $20,000 SELECT sp.Name, SUM(ISNULL(ssod.LineTotal,0.00)) as TotalSum FROM SalesLT.Product as sp JOIN SalesLT.SalesOrderDetail as ssod ON sp.ProductID = ssod.ProductID GROUP BY sp.Name HAVING SUM(ISNULL(ssod.LineTotal,0.00)) > 20000 ORDER BY TotalSum;
true
f3066de5bcf28cf46d9946cc88c021f10d70dd9c
SQL
cilt-uct/qna
/impl/src/sql/oracle/qna_sakai.sql
UTF-8
6,153
3.0625
3
[ "ECL-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
ALTER TABLE SAKAIDBA.QNA_ANSWERS DROP PRIMARY KEY CASCADE; DROP TABLE SAKAIDBA.QNA_ANSWERS CASCADE CONSTRAINTS; CREATE TABLE SAKAIDBA.QNA_ANSWERS ( ID VARCHAR2(255) NOT NULL, QUESTION_ID VARCHAR2(255) NOT NULL, OWNERID VARCHAR2(255) NOT NULL, ANSWERTEXT LONG NOT NULL, LASTMODIFIERID VARCHAR2(255) NOT NULL, DATELASTMODIFIED TIMESTAMP(6) DEFAULT NULL, DATECREATED TIMESTAMP(6) NOT NULL, APPROVED CHAR(1) NOT NULL, PRIVATEREPLY CHAR(1) NOT NULL, ANONYMOUS CHAR(1) NOT NULL ) TABLESPACE SAKAIDATA; ALTER TABLE SAKAIDBA.QNA_CATEGORIES DROP PRIMARY KEY CASCADE; DROP TABLE SAKAIDBA.QNA_CATEGORIES CASCADE CONSTRAINTS; CREATE TABLE SAKAIDBA.QNA_CATEGORIES ( ID VARCHAR2(255) NOT NULL, OWNERID VARCHAR2(255) NOT NULL, LOCATION VARCHAR2(255) NOT NULL, CATEGORYTEXT VARCHAR2(255) NOT NULL, DATELASTMODIFIED TIMESTAMP(6) NOT NULL, DATECREATED TIMESTAMP(6) NOT NULL, SORTORDER INTEGER DEFAULT NULL, HIDDEN CHAR(1) DEFAULT NULL ) TABLESPACE SAKAIDATA; ALTER TABLE SAKAIDBA.QNA_CUSTOM_EMAIL_LIST DROP PRIMARY KEY CASCADE; DROP TABLE SAKAIDBA.QNA_CUSTOM_EMAIL_LIST CASCADE CONSTRAINTS; CREATE TABLE SAKAIDBA.QNA_CUSTOM_EMAIL_LIST ( ID VARCHAR2(255) NOT NULL, OPTIONS_ID VARCHAR2(255) NOT NULL, OWNERID VARCHAR2(255) NOT NULL, EMAIL VARCHAR2(255) NOT NULL, DATECREATED TIMESTAMP(6) DEFAULT NULL ) TABLESPACE SAKAIDATA; ALTER TABLE SAKAIDBA.QNA_OPTIONS DROP PRIMARY KEY CASCADE; DROP TABLE SAKAIDBA.QNA_OPTIONS CASCADE CONSTRAINTS; CREATE TABLE SAKAIDBA.QNA_OPTIONS ( ID VARCHAR2(255) NOT NULL, OWNERID VARCHAR2(255) NOT NULL, LOCATION VARCHAR2(255) NOT NULL, DATELASTMODIFIED TIMESTAMP(6) DEFAULT NULL, ANONYMOUSALLOWED CHAR(1) DEFAULT NULL, MODERATED CHAR(1) DEFAULT NULL, EMAILNOTIFICATION CHAR(1) DEFAULT NULL, EMAILNOTIFICATIONTYPE VARCHAR2(255) DEFAULT NULL, DEFAULTSTUDENTVIEW VARCHAR2(255) DEFAULT NULL ) TABLESPACE SAKAIDATA; ALTER TABLE SAKAIDBA.QNA_QUESTIONS DROP PRIMARY KEY CASCADE; DROP TABLE SAKAIDBA.QNA_QUESTIONS CASCADE CONSTRAINTS; CREATE TABLE SAKAIDBA.QNA_QUESTIONS ( ID VARCHAR2(255) NOT NULL, CATEGORY_ID VARCHAR2(255) DEFAULT NULL, OWNERID VARCHAR2(255) NOT NULL, LASTMODIFIERID VARCHAR2(255) NOT NULL, LOCATION VARCHAR2(255) NOT NULL, QUESTIONTEXT LONG NOT NULL, VIEWS NUMBER(11) NOT NULL, DATELASTMODIFIED TIMESTAMP(6) NOT NULL, DATECREATED TIMESTAMP(6) NOT NULL, SORTORDER NUMBER(11) NOT NULL, ANONYMOUS CHAR(1) NOT NULL, PUBLISHED CHAR(1) NOT NULL, NOTIFY CHAR(1) NOT NULL, HIDDEN CHAR(1) DEFAULT NULL ) TABLESPACE SAKAIDATA; ALTER TABLE SAKAIDBA.QNA_ATTACHMENT DROP PRIMARY KEY CASCADE; DROP TABLE SAKAIDBA.QNA_ATTACHMENT CASCADE CONSTRAINTS; CREATE TABLE SAKAIDBA.QNA_ATTACHMENT ( ID VARCHAR2(255) NOT NULL, QUESTION_ID VARCHAR2(255) NOT NULL, ATTACHMENTID VARCHAR2(255) NOT NULL ) TABLESPACE SAKAIDATA; CREATE INDEX SAKAIDBA.FK63487CFAB9F9349F ON SAKAIDBA.QNA_ANSWERS (QUESTION_ID) TABLESPACE SAKAIDATA; CREATE INDEX SAKAIDBA.FKD08CBF742EDEC7B5 ON SAKAIDBA.QNA_CUSTOM_EMAIL_LIST (OPTIONS_ID) TABLESPACE SAKAIDATA; CREATE INDEX SAKAIDBA.FKE3F0F49224A87D9F ON SAKAIDBA.QNA_QUESTIONS (CATEGORY_ID) TABLESPACE SAKAIDATA; CREATE INDEX SAKAIDBA.FK2420E5EB9F9349F ON SAKAIDBA.QNA_ATTACHMENT (QUESTION_ID) TABLESPACE SAKAIDATA; DROP PUBLIC SYNONYM QNA_ANSWERS; CREATE PUBLIC SYNONYM QNA_ANSWERS FOR SAKAIDBA.QNA_ANSWERS; DROP PUBLIC SYNONYM QNA_CATEGORIES; CREATE PUBLIC SYNONYM QNA_CATEGORIES FOR SAKAIDBA.QNA_CATEGORIES; DROP PUBLIC SYNONYM QNA_CUSTOM_EMAIL_LIST; CREATE PUBLIC SYNONYM QNA_CUSTOM_EMAIL_LIST FOR SAKAIDBA.QNA_CUSTOM_EMAIL_LIST; DROP PUBLIC SYNONYM QNA_OPTIONS; CREATE PUBLIC SYNONYM QNA_OPTIONS FOR SAKAIDBA.QNA_OPTIONS; DROP PUBLIC SYNONYM QNA_QUESTIONS; CREATE PUBLIC SYNONYM QNA_QUESTIONS FOR SAKAIDBA.QNA_QUESTIONS; DROP PUBLIC SYNONYM QNA_ATTACHMENT; CREATE PUBLIC SYNONYM QNA_ATTACHMENT FOR SAKAIDBA.QNA_ATTACHMENT; ALTER TABLE SAKAIDBA.QNA_ANSWERS ADD ( PRIMARY KEY (ID) USING INDEX TABLESPACE SAKAIDATA); ALTER TABLE SAKAIDBA.QNA_CATEGORIES ADD ( PRIMARY KEY (ID) USING INDEX TABLESPACE SAKAIDATA); ALTER TABLE SAKAIDBA.QNA_CUSTOM_EMAIL_LIST ADD ( PRIMARY KEY (ID) USING INDEX TABLESPACE SAKAIDATA); ALTER TABLE SAKAIDBA.QNA_OPTIONS ADD ( PRIMARY KEY (ID) USING INDEX TABLESPACE SAKAIDATA); ALTER TABLE SAKAIDBA.QNA_QUESTIONS ADD ( PRIMARY KEY (ID) USING INDEX TABLESPACE SAKAIDATA); ALTER TABLE SAKAIDBA.QNA_ATTACHMENT ADD ( PRIMARY KEY (ID) USING INDEX TABLESPACE SAKAIDATA); GRANT SELECT,INSERT,UPDATE,DELETE ON SAKAIDBA.QNA_QUESTIONS TO SAKAI; GRANT SELECT,INSERT,UPDATE,DELETE ON SAKAIDBA.QNA_OPTIONS TO SAKAI; GRANT SELECT,INSERT,UPDATE,DELETE ON SAKAIDBA.QNA_CUSTOM_EMAIL_LIST TO SAKAI; GRANT SELECT,INSERT,UPDATE,DELETE ON SAKAIDBA.QNA_CATEGORIES TO SAKAI; GRANT SELECT,INSERT,UPDATE,DELETE ON SAKAIDBA.QNA_ANSWERS TO SAKAI; GRANT SELECT,INSERT,UPDATE,DELETE ON SAKAIDBA.QNA_ATTACHMENT TO SAKAI;
true
7209be8694e3a3213003846c2068da8fc4f83307
SQL
hellolizb/SpringcloudConfig
/2019-04-27 prp_file_download.sql
UTF-8
1,423
2.71875
3
[]
no_license
/* SQLyog 企业版 - MySQL GUI v8.14 MySQL - 5.5.5-10.0.10-MariaDB-V2.0R131D001-20160907-1111 : Database - channeldb ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`channeldb` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; USE `channeldb`; /*Data for the table `prp_file_download` */ insert into `prp_file_download`(`id`,`file_name`,`file_url`,`file_type`,`create_date`,`create_code`,`update_date`,`update_code`) values (1,'《客户授权书》PDF――版本一:适用于仅上线车险缴费实名认证的地区.pdf',NULL,'1','2019-03-12 16:56:44','1','2019-03-12 16:56:51','1'),(2,'《客户授权书》PDF――版本二:适用于同时上线车险缴费实名认证和投保短信验证码两个功能的地区.pdf',NULL,'1','2019-03-12 16:57:17','1','2019-03-12 16:57:21','1'); /*!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
3419c62d0542dc72253cda2a4755efdf080e51a3
SQL
Cloudyrl/bd2-scripts
/SQL/create.sql
UTF-8
13,444
2.890625
3
[]
no_license
/* ------------------------TDA------------------------ */ / Create or Replace type Datos_persona_de_contacto as Object( Nombre Varchar2(50), Apellido Varchar2(50), Cargo Varchar2(50), Email Varchar2(500) ) / Create or Replace type Datos_telefono as Object( Codigo_area Number(5), Codigo_internacional Number(5), Numero Number(10) ) / Create or Replace type Datos_direccion as Object( Calle Varchar2(500), Avenida Varchar2(500), Codigo_postal Number(10), Urbanizacion Varchar2(500), Ciudad Varchar2(50) ) / Create or Replace type Lugar as Object( Pais Varchar2(50), Ciudad Varchar2(50) ) / Create or Replace type Hechos_hist as Object( Año Date, Hechos Varchar2(1000) ) / Create or Replace type Tipo_valor as Object( Año Date, Valor Float ) / Create or Replace type Valoracion as Object( Nombreelemento Varchar2(50), Valor Number(10), Observacion Varchar2(500) ) / Create or Replace type Costo as Object( Cantmuestras Number(10), Valor Float, Pais Varchar2(50) ) / Create or Replace type Premio as Object( Nombre Varchar2(50), Descripcion Varchar2(500), Tipo Varchar2(50), Premioenmoneda Number(10), Posicion Number(10) ) / Create or Replace type Datos_contacto_telefono_va as varray(3) of Datos_telefono / Create or Replace type Personal_contacto_va as varray(5) of Datos_persona_de_contacto / Create or Replace type Tipo_valor_distribucion_exp as varray(5) of Tipo_valor / Create or Replace type Datos_contacto as Object( Direccion Datos_direccion, Correo_electronico Varchar2(500), Pagina_web Varchar2(500), Telefonos Datos_contacto_telefono_va, Pesonal_contacto Personal_contacto_va ) / Create or Replace type Distribucion_exp as Object( Tipovalor Tipo_valor, Pais Varchar2(50) ) / Create or Replace type Calificacion as Object( Nombrecritica Varchar2(50), Tipovalor Tipo_valor ) / Create or Replace type Escala as Object( Elemento Varchar2(50), Valorini Number(10), Valorfin Number(10), Clasificacion Varchar2(50) ) / Create or Replace type Unidadmonetaria as Object( Nombre Varchar2(50), Simbolo Varchar2(5) ) / Create or Replace type Superficie_ocupada_pais_nt as table of Tipo_valor / Create or Replace type Produccionanual_pais_nt as table of Tipo_valor / Create or Replace type Exportacionanual_pais_nt as table of Distribucion_exp / Create or Replace type Unidadmonetaria_pais_nt as table of Unidadmonetaria / Create or Replace type Premio_concurso_nt as table of Premio / Create or Replace type Escala_concurso_nt as table of Escala / Create or Replace type Hechos_hist_bodega_nt as table of Hechos_hist / Create or Replace type Tipo_valor_bodega_nt as table of Tipo_valor / Create or Replace type Distribucion_exp_bodega_nt as table of Distribucion_exp / Create or Replace type Calificacion_marca_nt as table of Calificacion / Create or Replace type Tipo_valor_marca_nt as table of Tipo_valor / Create or Replace type Distribucion_exp_marca_nt as table of Distribucion_exp / Create or Replace type Porcentajevol_clasificacion_va as varray(15) of Number(15) / Create or Replace type Curricula_catador_experto_nt as table of Hechos_hist / Create or Replace type Publicaciones_catador_exp_va as varray(5) of Varchar2(100) / Create or Replace type Curricula_catador_aprendiz_nt as table of Hechos_hist / Create or Replace type Publicaciones_catador_apr_va as varray(5) of Varchar2(100) / Create or Replace type Costo_calendario_nt as table of Costo / Create or Replace type Unidadmonetaria_calendario_nt as table of Unidadmonetaria / Create or Replace type Valor_cata_valor_muestra_m_nt as table of Valoracion / Create or Replace type Valoracion_cata_valor_apr_nt as table of Valoracion / Create or Replace type Premio_inscripcion_nt as table of Premio / Create or Replace type Premio_muestra_compite_nt as table of Premio / Create or Replace type Nombre_variedad_uva_va as varray(5) of Varchar2(50) / /* ---------------------FIN TDA---------------------- */ Create Table Pais_productor ( Clave Integer Not Null, Nombre Varchar2(50) Not Null, Superficie_ocupada_vinedo Superficie_ocupada_pais_nt , Produccioanual Produccionanual_pais_nt , Exportacionanual Exportacionanual_pais_nt , Unidadmonetaria Unidadmonetaria , Continente Varchar2(50) Not Null, Mapasregiones Blob, Descripcion Varchar2(500), Constraint pk_pais_productor PRIMARY KEY(Clave) ) Nested Table Superficie_ocupada_vinedo store as Sup_ocupada_pais_nt Nested Table Produccioanual store as Producanual_pais_nt Nested Table Exportacionanual store as Expanual_pais_nt ; Create Table Region ( Clave Integer Not Null, Nombre Varchar2(50) Not Null, Descripcion Varchar2(500), Clave_pais_productor Integer Not Null, Constraint pk_region PRIMARY KEY(Clave) ); Create Table Denominacion_origen ( Clave Integer Not Null, Nombre Varchar2(50) Not Null, Descripcion Varchar2(500), Clave_region Integer Not Null, Clave_variedad_uva Integer, Clave_vinedo Integer Not Null, Constraint pk_denominacion_origen PRIMARY KEY(Clave) ); Create Table Organizador ( Clave Integer Not Null, Nombre Varchar2(50) Not Null, Descripcion Varchar2(500), Constraint pk_organizador PRIMARY KEY(Clave) ); Create Table Organizador_concurso ( Clave_propio Integer Not Null, Clave_organizador Integer Not Null, Clave_concurso Integer Not Null, Constraint pk_organizador_concurso PRIMARY KEY(Clave_propio) ); Create Table Organizador_pais ( Clave_propio Integer Not Null, Clave_organizador Integer Not Null, Clave_pais_productor Integer Not Null, Constraint pk_organizador_pais PRIMARY KEY(Clave_propio) ); Create Table Concurso ( Clave Integer Not Null, Nombre Varchar2(50) Not Null, Tipoconcurso Varchar2(50) Not Null, Tipocata Varchar2(50), Nacional Varchar2(1) Not Null, Caracteristicas Varchar2(500) Not Null, Premios Premio_concurso_nt , Escalas Escala_concurso_nt , Constraint pk_concurso PRIMARY KEY(Clave) ) Nested Table Premios store as Premios_concurso_nt Nested Table Escalas store as Escalas_concurso_nt ; Create Table Bodega ( Clave Integer Not Null, Nombre Varchar2(50) Not Null, Historia Hechos_hist_bodega_nt, Fechafundacion Date Not Null, Mision Varchar2(1000) Not Null, Descripcion_vinos Varchar2(1000) Not Null, Datoscontacto Datos_contacto, Produccioanual Tipo_valor_bodega_nt, Exportacionanual Distribucion_exp_bodega_nt, Clave_dueño Integer, Clave_pais_productor Integer Not Null, Constraint pk_bodega PRIMARY KEY(Clave) ) Nested Table Historia store as Hechos_hist_bodegas_nt Nested Table Produccioanual store as Tipo_valor_bodegas_nt Nested Table Exportacionanual store as Distribucion_exp_bodegas_nt ; Create Table Marca ( Clave Integer Not Null, Nombre Varchar2(50) Not Null, Elaboracion Varchar2(1000) Not Null, Cata_propia Varchar2(1000) Not Null, Maridaje Varchar2(1000) Not Null, Temperatura Number(10) Not Null, Unidad_temperatura Varchar2(5) Not Null, Ventana_de_consumo Number(10) Not Null, Grado_de_alcohol Float Not Null, Acidez_total Float Not Null, Ph Float Not Null, Color Varchar2(50) Not Null, Imagen Blob, Contacto_madera Varchar2(1) Not Null, Tipo_tapon Varchar2(50) Not Null, Criticas Calificacion_marca_nt , Produccionaño Tipo_valor_marca_nt, Exportacionaño Distribucion_exp_marca_nt , Tiempomaduracionmeses Number(5) Not Null, Clave_bodega Integer Not Null, Clave_clasificacion Integer Not Null, Constraint pk_marca PRIMARY KEY(Clave) ) Nested Table Criticas store as Calificacion_marcas_nt Nested Table Produccionaño store as Tipo_valor_marcas_nt Nested Table Exportacionaño store as Distribucion_exp_marcas_nt ; Create Table Clasificacion ( Clave Integer Not Null, Nombre Varchar2(100) Not Null, Nivel Varchar2(50) Not Null, Porcentaje_vol Porcentajevol_clasificacion_va , Clave_clasificacion Integer, Constraint pk_clasificacion PRIMARY KEY(Clave) ); Create Table Presentacion ( Clave Integer Not Null, Tipo Varchar2(50) Not Null, Unidadesencaja Number(10), Clave_marca Integer Not Null, Constraint pk_presentacion PRIMARY KEY(Clave) ); Create Table Historico_precio ( Clave Integer Not Null, Año Date Not Null, Precio Float Not Null, Clave_presentacion Integer Not Null, Clave_cosecha Integer Not Null, Constraint pk_historico_precio PRIMARY KEY(Clave) ); Create Table Cosecha ( Clave Integer Not Null, Año Date Not Null, Clasificacion Varchar2(50) Not Null, Clave_vinedo Integer Not Null, Constraint pk_cosecha PRIMARY KEY(Clave) ); Create Table Catador_experto ( Clave Integer Not Null, Primer_nombre Varchar2(50) Not Null, Segundo_nombre Varchar2(50), Primer_apellido Varchar2(50) Not Null, Segundo_apellido Varchar2(50), Fecha_nacimiento Date Not Null, Lugar_realizada Lugar, Genero Varchar2(10) Not Null, Datoscontacto Datos_contacto, Curricula Curricula_catador_experto_nt, Publicacion Publicaciones_catador_exp_va, Clave_pais_productor Integer Not Null, Constraint pk_catador_experto PRIMARY KEY(Clave) ) Nested Table Curricula store as Curriculas_catador_experto_nt ; Create Table Catador_aprendiz ( Clave Integer Not Null, Primer_nombre Varchar2(50) Not Null, Segundo_nombre Varchar2(50) Not Null, Primer_apellido Varchar2(50) Not Null, Segundo_apellido Varchar2(50) Not Null, Fecha_nacimiento Date Not Null, Lugar_realizada Lugar , Genero Varchar2(10) Not Null, Datoscontacto Datos_contacto , Curricula Curricula_catador_aprendiz_nt, Publicacion Publicaciones_catador_apr_va, Clave_pais_productor Integer Not Null, Constraint pk_catador_aprendiz PRIMARY KEY(Clave) ) Nested Table Curricula store as Curriculas_catador_aprendiz_nt ; Create Table Calendario ( Clave Integer Not Null, Fechai Date Not Null, Fechaf Date Not Null, Fechaliminscripcion Date Not Null, Fechalimmuestra Date Not Null, Emailenvioinscripcion Varchar2(500) Not Null, Direcionenviomuestras Datos_direccion , Lugar_realizada Lugar , Costo Costo_calendario_nt , Condiciondepago Varchar2(50), Unidadmonetaria Unidadmonetaria_calendario_nt , Clave_concurso Integer Not Null, Constraint pk_calendario PRIMARY KEY(Clave) ) Nested Table Costo store as Costo_calendarios_nt Nested Table Unidadmonetaria store as Unidadmonetaria_calendarios_nt ; Create Table Jueces ( Clave Integer Not Null, Clave_calendario Integer Not Null, Clave_catador_experto Integer Not Null, Constraint pk_jueces PRIMARY KEY(Clave) ); Create Table Cata_valoracion_muestra_marca ( Clave Integer Not Null, Fecha Date Not Null, Valoracion Valor_cata_valor_muestra_m_nt , Sumatoria Number(10) Not Null, Clave_jueces Integer Not Null, Clave_muestra_compite Integer Not Null, Constraint pk_cata_valor_muestra_m PRIMARY KEY(Clave) ) Nested Table Valoracion store as Valor_cata_valor_muestra_ms_nt ; Create Table Cata_valor_aprendiz ( Clave Integer Not Null, Fecha Date Not Null, Valoracion Valoracion_cata_valor_apr_nt , Sumatoria Number(10) Not Null, Clave_inscripcion Integer Not Null, Clave_muestra_catador Date Not Null, Constraint pk_cata_valor_aprediz PRIMARY KEY(Clave) ) Nested Table Valoracion store as Valoracion_cata_valor_aprs_nt ; Create Table Inscripcion ( Clave Integer Not Null, Fecha_inscripcion Date Not Null, Premio Premio_inscripcion_nt, Clave_bodega Integer, Clave_catador_aprendiz Integer, Clave_calendario Integer Not Null, Constraint pk_inscripcion PRIMARY KEY(Clave) ) Nested Table Premio store as Premio_inscripciones_nt ; Create Table Muestra_compite ( Clave Integer Not Null, Añada Date Not Null, Premio Premio_muestra_compite_nt, Clave_marca Integer Not Null, Clave_inscripcion Integer Not Null, Constraint pk_muestra_compite PRIMARY KEY(Clave) ) Nested Table Premio store as Premio_muestra_compites_nt ; Create Table Muestra_catador ( Añada Date Not Null, Sumatoriaexperto Number(10) Not Null, Clave_marca Integer Not Null, Clave_jueces Integer Not Null, Constraint pk_muestra_catador PRIMARY KEY(Añada) ); Create Table Variedad_uva ( Clave Integer Not Null, Nombre Nombre_variedad_uva_va, Descripcion Varchar2(50), Tipodeuva Varchar2(50) Not Null, Clave_vinedo Integer Not Null, Constraint pk_variedad_uva PRIMARY KEY(Clave) ); Create Table Vinedo ( Clave_propio Integer Not Null, Clave_bodega Integer Not Null, Constraint pk_vinedo PRIMARY KEY(Clave_propio) ); CREATE OR REPLACE directory image_dir AS 'C:\Users\Annemarie\Desktop\bd2-scripts\Imagenes Vinos\Imagenes Vinos'; --CREATE OR REPLACE directory image_dir AS 'C:\Users\Cloudy\Desktop\db2-scripts\bd2-scripts\Imagenes Vinos\Imagenes Vinos'; --Para correrlo si les dice "insufficient privileges" corran los siguientes comando en SQLplus --"connect system/manager as SYSDBA;" y "grant create any directory to hr;" vuelven a correr el --crear directorio y se los deberia crear
true
2674de90660ee82df471a8272608306fcaa53e65
SQL
polterguy/magic
/backend/files/misc/sqlite/magic.sql
UTF-8
4,842
3.703125
4
[ "MIT", "LGPL-3.0-only", "GPL-3.0-only" ]
permissive
/* * This MySQL script creates a database for you, serving * as Magic's main database. */ /* * Creates the authentication database in PgSQL. */ /* * Creating users table. */ create table "users" ( "username" varchar(256) not null primary key collate nocase, "password" varchar(256) not null, "locked" boolean not null default false, "created" timestamp not null default current_timestamp ); /* * Creating roles table. */ create table "roles" ( "name" varchar(45) not null primary key collate nocase, "description" varchar(256) null collate nocase ); /* * Creating association between roles and users through users_roles table. */ create table "users_roles" ( "role" varchar(45) not null collate nocase, "user" varchar(256) not null collate nocase, constraint "roles_fky" foreign key ("role") references "roles" ("name") on delete cascade, constraint "users_fky" foreign key ("user") references "users" ("username") on delete cascade, primary key("role", "user") ); create index "users_roles_user_idx" on "users_roles" ("user"); /* * Inserting some roles into our roles table. */ insert into roles (name, description) values ('root', 'A user that has complete access to everything in the system'); insert into roles (name, description) values ('admin', 'An administrator with elevated rights to do things other cannot do'); insert into roles (name, description) values ('guest', 'A confirmed user with some elevated rights'); insert into roles (name, description) values ('reset-password', 'A special role that only allows the user to change his password'); insert into roles (name, description) values ('unconfirmed', 'An unconfirmed user that has severely restricted access'); insert into roles (name, description) values ('blocked', 'A user that has been blocked from site entirely'); /* * Tasks and task scheduler tables */ /* * Creating tasks table. */ create table tasks ( id varchar(256) not null primary key collate nocase, description text null collate nocase, hyperlambda text not null collate nocase, created timestamp not null default current_timestamp ); create unique index "tasks_id_idx" on "tasks" ("id"); /* * Creating task_due table. */ create table task_due ( id integer not null primary key autoincrement, task varchar(256) not null collate nocase, due timestamp not null, repeats text null, constraint task_due_task_fky foreign key (task) references tasks (id) on delete cascade ); create index "task_due_task_idx" on "task_due" ("task"); /* * Logging tables. */ /* * Creating log table. */ create table log_entries ( id integer not null primary key autoincrement, created timestamp not null default current_timestamp, type varchar(10) not null collate nocase, content text not null collate nocase, exception text null collate nocase ); /* * Cryptography tables. */ /* * Creating crypto_keys table for holding public cryptography keys. */ create table crypto_keys ( id integer primary key autoincrement not null, subject varchar(120) not null collate nocase, email varchar(120) not null collate nocase, domain varchar(250) null collate nocase, type varchar(20) not null collate nocase, fingerprint varchar(120) not null collate nocase, content text not null, vocabulary text not null, imported timestamp not null default current_timestamp, enabled boolean not null default false ); create index "crypto_keys_subject_idx" on "crypto_keys" ("subject"); create index "crypto_keys_email_idx" on "crypto_keys" ("email"); /* * Creating crypto_invocations table for holding invocations associated * with some public key. */ create table crypto_invocations ( id integer primary key autoincrement not null, crypto_key integer not null collate nocase, request_id varchar(250) not null collate nocase, request text not null collate nocase, request_raw text not null, response text not null, created timestamp not null default current_timestamp, constraint "request_id_UNIQUE" unique ("request_id"), constraint "crypto_key_fky" foreign key ("crypto_key") references "crypto_keys" ("id") on delete cascade ); create index "crypto_invocations_crypto_key_idx" on "crypto_invocations" ("crypto_key"); /* * Creating association table between users and crypto_keys. */ create table "users_crypto_keys" ( "username" varchar(256) not null collate nocase, "key_id" integer not null, constraint "username_fky" foreign key ("username") references "users" ("username") on delete cascade, constraint "key_id_fky" foreign key ("key_id") references "crypto_keys" ("id") on delete cascade, primary key("username", "key_id") ); create index "users_crypto_keys_username_idx" on "users_crypto_keys" ("username"); create index "users_crypto_keys_key_id_idx" on "users_crypto_keys" ("key_id");
true
afd31079895cba1ed187db28921be2b6bbd79841
SQL
aokazuki/bookmarkapp-usermng
/select, insertを用いたアプリ作成_AoyamaKazuki_01/{01}.{KazukiAoyama}.sql
UTF-8
2,325
2.640625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.7 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Mar 31, 2021 at 11:56 PM -- Server version: 5.7.32 -- PHP Version: 7.4.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Database: `gs_bookmark_db` -- -- -------------------------------------------------------- -- -- Table structure for table `gs_bm_table` -- CREATE TABLE `gs_bm_table` ( `id` int(12) NOT NULL, `bookname` varchar(64) NOT NULL, `bookurl` text NOT NULL, `bookcomment` text NOT NULL, `addtime` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `gs_bm_table` -- INSERT INTO `gs_bm_table` (`id`, `bookname`, `bookurl`, `bookcomment`, `addtime`) VALUES (1, '新装版 竜馬がゆく (1)', 'https://www.amazon.co.jp/%E6%96%B0%E8%A3%85%E7%89%88-%E7%AB%9C%E9%A6%AC%E3%81%8C%E3%82%86%E3%81%8F-%E6%96%87%E6%98%A5%E6%96%87%E5%BA%AB-%E5%8F%B8%E9%A6%AC-%E9%81%BC%E5%A4%AA%E9%83%8E/dp/4167105675', 'おばあちゃん家で最初に読んだ本', '2021-04-01 08:45:25'), (2, '新装版 竜馬がゆく (2)', 'https://www.amazon.co.jp/%E6%96%B0%E8%A3%85%E7%89%88-%E7%AB%9C%E9%A6%AC%E3%81%8C%E3%82%86%E3%81%8F-%E6%96%87%E6%98%A5%E6%96%87%E5%BA%AB-%E5%8F%B8%E9%A6%AC-%E9%81%BC%E5%A4%AA%E9%83%8E/dp/4167105683/ref=pd_bxgy_img_2/355-9110616-8127202?_encoding=UTF8&pd_rd_i=4167105683&pd_rd_r=2505fdb9-4264-41ba-bd7e-9baed7ee8644&pd_rd_w=0nyoF&pd_rd_wg=ZqeRH&pf_rd_p=e64b0a81-ca1b-4802-bd2c-a4b65bccc76e&pf_rd_r=TWG129QYH1WXNPMCF6Z9&psc=1&refRID=TWG129QYH1WXNPMCF6Z9', '続き', '2021-04-01 08:47:01'), (3, 'ブラック・ジャック(1)', 'https://www.amazon.co.jp/%E3%83%96%E3%83%A9%E3%83%83%E3%82%AF%E3%83%BB%E3%82%B8%E3%83%A3%E3%83%83%E3%82%AF-1-%E6%89%8B%E5%A1%9A%E6%B2%BB%E8%99%AB%E6%BC%AB%E7%94%BB%E5%85%A8%E9%9B%86-%E6%89%8B%E5%A1%9A-%E6%B2%BB%E8%99%AB/dp/4061087517/ref=tmm_other_meta_binding_swatch_0?_encoding=UTF8&qid=1617234775&sr=1-3', '実家で初めて読んだ漫画でした', '2021-04-01 08:54:24'); -- -- Indexes for dumped tables -- -- -- Indexes for table `gs_bm_table` -- ALTER TABLE `gs_bm_table` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `gs_bm_table` -- ALTER TABLE `gs_bm_table` MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
true
a3cd24201c790175aad5cf844f6eb6ebfea08c23
SQL
radtek/tensordev
/sql/db_cache_advice.sql
UTF-8
1,115
3.453125
3
[]
no_license
-- ----------------------------------------------------------------------------------- -- File Name : db_cache_advice.sql -- Description : Predicts how changes to the buffer cache will affect physical reads -- Requirements : Access to the DBA views. -- Call Syntax : @db_cache_advice.sql -- Last Modified: 02/04/2012 -- ----------------------------------------------------------------------------------- COLUMN SIZE_FOR_ESTIMATE FORMAT 999,999,999,999 HEADING 'CACHE SIZE (MB)' COLUMN BUFFERS_FOR_ESTIMATE FORMAT 999,999,999 HEADING 'BUFFERS' COLUMN ESTD_PHYSICAL_READ_FACTOR FORMAT 999.90 HEADING 'ESTD PHYS|READ FACTOR' COLUMN ESTD_PHYSICAL_READS FORMAT 999,999,999,999 HEADING 'ESTD PHYS| READS' SELECT SIZE_FOR_ESTIMATE, BUFFERS_FOR_ESTIMATE, ESTD_PHYSICAL_READ_FACTOR, ESTD_PHYSICAL_READS FROM V$DB_CACHE_ADVICE WHERE NAME = 'DEFAULT' AND BLOCK_SIZE = (SELECT VALUE FROM V$PARAMETER WHERE NAME = 'DB_BLOCK_SIZE') AND ADVICE_STATUS = 'ON' ORDER BY 1;
true
c8cff30db900b29665b66668e60fdfdecd461b8b
SQL
gogotea55t/bbp-jiriki-backend
/src/main/resources/db/migration/V1__Initial_version.sql
UTF-8
1,200
3.65625
4
[]
no_license
CREATE TABLE IF NOT EXISTS USERS ( USER_ID VARCHAR(10) PRIMARY KEY, USER_NAME VARCHAR(15) NOT NULL )/*! CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */; CREATE TABLE IF NOT EXISTS SONGS ( SONG_ID VARCHAR(10) PRIMARY KEY, JIRIKI_RANK INT, SONG_NAME VARCHAR(60) NOT NULL, CONTRIBUTOR VARCHAR(20) NOT NULL, INSTRUMENT VARCHAR(15) NOT NULL )/*! CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */; CREATE TABLE IF NOT EXISTS SCORES ( SCORE_ID INT PRIMARY KEY AUTO_INCREMENT, SONGS_SONG_ID VARCHAR(10), USERS_USER_ID VARCHAR(10), SCORE TINYINT UNSIGNED, FOREIGN KEY (SONGS_SONG_ID) references SONGS(SONG_ID) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (USERS_USER_ID) references USERS(USER_ID) ON UPDATE CASCADE ON DELETE CASCADE, UNIQUE SCORE_HOLDER_INDEX (SONGS_SONG_ID, USERS_USER_ID) )/*! CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */; CREATE TABLE IF NOT EXISTS TWITTER_USERS ( TWITTER_USER_ID VARCHAR(30) PRIMARY KEY, USERS_USER_ID VARCHAR(10), FOREIGN KEY (USERS_USER_ID) references USERS(USER_ID) ON UPDATE CASCADE ON DELETE CASCADE )/*! CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */;
true
789c85226e1a73c20cfe7ec9e8aa5ff1bd69dd0c
SQL
9090ID/bidikmisi
/bidikmisi.sql
UTF-8
1,681
2.953125
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Jun 05, 2017 at 04:06 PM -- Server version: 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: `bidikmisi` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id_user` int(11) NOT NULL, `username` varchar(30) NOT NULL, `password` text NOT NULL, `usertype` enum('admin','operator') NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id_user`, `username`, `password`, `usertype`, `created_at`, `updated_at`) VALUES (1, 'admin', '$2y$10$.TMBVGXthJsBP6MmiqbrQ./xZt.hSu6T.7JtnBgCY4T5cpsZpVQhq', 'admin', '2017-06-05 13:37:14', '2017-06-05 06:40:54'); -- -- Indexes for dumped tables -- -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id_user`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; /*!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
1a408637a900c4bbb2c60e072e1fcfb07289eafc
SQL
Mnrt-Jem/-PHP-site-journee-pedagogique
/projet_peda.sql
UTF-8
4,259
3.09375
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Hôte : 127.0.0.1:3306 -- Généré le : mer. 18 oct. 2017 à 13:54 -- Version du serveur : 5.7.19 -- Version de PHP : 5.6.31 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `projet_peda` -- -- -------------------------------------------------------- -- -- Structure de la table `accueil` -- DROP TABLE IF EXISTS `accueil`; CREATE TABLE IF NOT EXISTS `accueil` ( `id_accueil` int(11) NOT NULL AUTO_INCREMENT, `text_accueil` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id_accueil`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Structure de la table `contact` -- DROP TABLE IF EXISTS `contact`; CREATE TABLE IF NOT EXISTS `contact` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(32) COLLATE utf8_bin DEFAULT NULL, `email` varchar(32) COLLATE utf8_bin DEFAULT NULL, `message` varchar(180) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -------------------------------------------------------- -- -- Structure de la table `lien_youtube` -- DROP TABLE IF EXISTS `lien_youtube`; CREATE TABLE IF NOT EXISTS `lien_youtube` ( `id_ly` int(11) NOT NULL AUTO_INCREMENT, `lien` varchar(255) COLLATE utf8_bin NOT NULL, `nom_lien` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id_ly`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Déchargement des données de la table `lien_youtube` -- INSERT INTO `lien_youtube` (`id_ly`, `lien`, `nom_lien`) VALUES (3, 'https://www.youtube.com/embed/oAiseNw9M18', 'vidéo saint vincent '); -- -------------------------------------------------------- -- -- Structure de la table `login` -- DROP TABLE IF EXISTS `login`; CREATE TABLE IF NOT EXISTS `login` ( `id_log` int(11) NOT NULL AUTO_INCREMENT, `nom_log` varchar(32) COLLATE utf8_bin NOT NULL, `mdp_log` varchar(32) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id_log`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Déchargement des données de la table `login` -- INSERT INTO `login` (`id_log`, `nom_log`, `mdp_log`) VALUES (5, 'test@test', 'test'), (2, 'admin', 'passwordadmin'); -- -------------------------------------------------------- -- -- Structure de la table `programme` -- DROP TABLE IF EXISTS `programme`; CREATE TABLE IF NOT EXISTS `programme` ( `id_prog` int(11) NOT NULL AUTO_INCREMENT, `nom_prog` varchar(80) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `img_prog` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `text_prog` text CHARACTER SET utf8 COLLATE utf8_bin, PRIMARY KEY (`id_prog`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `programme` -- INSERT INTO `programme` (`id_prog`, `nom_prog`, `img_prog`, `text_prog`) VALUES (1, 'pilo', NULL, 'pilo2 bite'), (4, 'Jm le plus beau', NULL, 'jm est beau'); -- -------------------------------------------------------- -- -- Structure de la table `temoignage` -- DROP TABLE IF EXISTS `temoignage`; CREATE TABLE IF NOT EXISTS `temoignage` ( `id_temoignage` int(11) NOT NULL AUTO_INCREMENT, `img_temoignage` varchar(255) NOT NULL, PRIMARY KEY (`id_temoignage`) ) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `temoignage` -- INSERT INTO `temoignage` (`id_temoignage`, `img_temoignage`) VALUES (1, 'test1.png'), (2, 'test2.png'), (3, 'test3.png'), (4, 'test4.png'), (5, 'test5.png'), (6, 'test6.png'), (7, 'test7.png'), (8, 'test8.png'), (9, 'test9.png'), (10, 'test10.png'), (11, 'test11.png'); 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
cd04d576a57682d2b9df1bc4561a17de2307de5a
SQL
thebravoman/elsys-db-practices
/exam2016/exam20160218/a/Lubomir_Yankov_12A_16/selects1.sql
UTF-8
189
3.734375
4
[]
no_license
SELECT Category.id FROM Category JOIN User ON Category.id = User.category_id JOIN Tag_User ON User.id = Tag_User.user_id JOIN Tag ON Tag_User.tag_id = Tag.id WHERE Tag.id = 1
true
a6520e26e8b4211377218ecd956656d2573c4b64
SQL
pedrodebruin/SQL_scripts
/exercises/week2_selects.sql
UTF-8
1,078
4.125
4
[]
no_license
-- The queries below use the data in -- Employees.csv, Departments.csv, Jobs.csv, Locations.csv, JobsHistory.csv -- which fill tables made with Script_Create_Tables.sql -- Query 1: Retrieve all employees whose address is in Elgin,IL select * from EMPLOYEES where ADDRESS like '%Elgin,%IL%'; -- Query 2: Retrieve all employees who were born during the 1970's. select * from EMPLOYEES where B_DATE like '197%'; -- Query 3: Retrieve all employees in department 5 whose salary is between 60000 and 70000 . select * from EMPLOYEES where DEP_ID=5 AND SALARY between 60000 and 70000; -- Query 4: Retrieve a list of employees ordered by department name, and within -- each department ordered alphabetically in descending order by last name. select F_NAME, L_NAME, DEP_NAME from EMPLOYEES, DEPARTMENTS group by F_NAME, L_NAME, DEP_NAME order by DEP_NAME, L_NAME desc; -- Query 5: Retrieve the department number, the number of employees in the -- department, and their average salary. select DEP_ID, count(*) as N_EMP, AVG(SALARY) as MEAN_SALARY from EMPLOYEES group by DEP_ID;
true
adf218a1843778e035e971b4e654515e7a3de8e0
SQL
alekseinovikov/Blog
/backend/resources/migrations/3.sql
UTF-8
275
2.921875
3
[]
no_license
ALTER TABLE posts ADD COLUMN created_at timestamptz NOT NULL DEFAULT NOW(), ADD COLUMN updated_at timestamptz NOT NULL DEFAULT NOW(); CREATE TRIGGER posts_updated_at_trigger BEFORE UPDATE ON posts FOR EACH ROW EXECUTE PROCEDURE trigger_set_updated_at();
true
c9eea855566b9095e032da9455e3a9bfc3423bf2
SQL
mhrafi66/Student-Information-System-
/sql files/check teacher.sql
UTF-8
252
2.6875
3
[]
no_license
CREATE or replace procedure check_teacher(input_id in number, x out varchar2) as temp varchar2(30); begin select password into temp from teacher WHERE id = input_id; x:=temp; exception when no_data_found then x:='not found'; end; /
true
2769d72d01644990b72c6081d0274e0d6007e8c6
SQL
Sumei1009/T25
/htdocs/bid.sql
UTF-8
206
2.625
3
[]
no_license
CREATE TABLE bid( phone_number INTEGER REFERENCES appuser(phone_number), rid_number VARCHAR(10) REFERENCES ride_generate(rid_number), status BOOLEAN, point INTEGER, PRIMARY KEY (phone_number,rid_number) );
true
479b4545cc547e6aa74e229c9532a509fe042fe1
SQL
crgarzon1/Posgrado
/src/PLSQL/PROD/POSGRADO/PKG_CTI_DASHBOARD_POSGRADOS.sql
UTF-8
34,276
3.125
3
[]
no_license
create or replace PACKAGE BODY PKG_CTI_DASHBOARD_POSGRADOS AS /* OBTIENE LOS PRIMEROS 10 ESTUDIANTES QUE CUMPLAN CON EL CRITERIO DE BUSQUEDA. EL CRITERIO DE BUSQUEDA PUEDE SER EL NOMBRE, EL NUMERO DE DOCUMENTO O EL CODIGO ESTUDIANTIL. @param P_CRITERIO_BUSQUEDA VARCHAR2 => C = codigo estudiantil, D = Numero de documento, N = Nombre o apellido. @param P_VALOR => VALOR DE BUSQUEDA (CODIGO ESTUDIANTIL, NOMBRE O NUMERO DE DOCUMENTO.) */ PROCEDURE BUSCAR_ESTUDIANTE( P_CRITERIO_BUSQUEDA VARCHAR2, P_VALOR VARCHAR2, P_CODIGO_FACULTAD VARCHAR2, P_JORNADA_FACULTAD VARCHAR2 ) IS V_BODY JSON_LIST; V_ERROR JSON; BEGIN POSTGRADO.PKG_HTML.CORSHEADERS(); V_BODY := JSON_LIST(); -- OBTENCION DE ESTUDIANTES QUE CUMPLAN CON LOS CRITERIOS DE BUSQUEDA. --D = Documento --C = Codigo --N = Nombre IF P_CRITERIO_BUSQUEDA = 'D' THEN FOR ESTUDIANTE IN (SELECT E.CODIGO FROM POSTGRADO.B_ESTUDIANTES E INNER JOIN POSTGRADO.DATOS_PERSONALES DP ON E.CODIGO = DP.CODIGO_ESTUDIANTE WHERE (LOWER(DP.NUMERO_DOCUMENTO) LIKE '%' || LOWER(P_VALOR) || '%') AND ROWNUM <= 10 AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD) LOOP JSON_LIST.APPEND (V_BODY, PKG_UTILS.GETESTUDIANTE(ESTUDIANTE.CODIGO).TO_JSON_VALUE); END LOOP; ELSIF P_CRITERIO_BUSQUEDA = 'C' THEN FOR ESTUDIANTE IN (SELECT E.CODIGO FROM POSTGRADO.B_ESTUDIANTES E WHERE (E.CODIGO LIKE '%' || P_VALOR || '%') AND ROWNUM <= 10 AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD) LOOP JSON_LIST.APPEND (V_BODY, PKG_UTILS.GETESTUDIANTE(ESTUDIANTE.CODIGO).TO_JSON_VALUE); END LOOP; ELSIF P_CRITERIO_BUSQUEDA = 'N' THEN FOR ESTUDIANTE IN (SELECT E.CODIGO FROM POSTGRADO.B_ESTUDIANTES E INNER JOIN POSTGRADO.DATOS_PERSONALES DP ON E.CODIGO = DP.CODIGO_ESTUDIANTE WHERE ( LOWER(E.NOMBRE) LIKE '%' || LOWER(P_VALOR) ||'%') AND ROWNUM <= 10 AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD) LOOP JSON_LIST.APPEND (V_BODY, PKG_UTILS.GETESTUDIANTE(ESTUDIANTE.CODIGO).TO_JSON_VALUE); END LOOP; END IF; JSON_LIST.HTP(V_BODY, FALSE); EXCEPTION WHEN OTHERS THEN V_ERROR := JSON (); JSON.PUT (V_ERROR, 'status', 'Error'); JSON.PUT (V_ERROR, 'message', SQLCODE || ' --- ' || SUBSTR (SQLERRM, 1, 200)); JSON.HTP(V_ERROR); END BUSCAR_ESTUDIANTE; /* OBTIENE LOS SIGUIENTES INDICADORES DE LAS INSCRIPCIONES DE UN PROGRAMA ACADEMICO: - HABEAS DATA. - FORMULARIO 1. - FORMULARIO 2. - PAGO DE INSCRIPCI�N. - ENTREVISTADOS. - ADMITIDOS. - MATRICULADOS. @param P_CODIGO_FACULTAD VARCHAR2 => CODIGO FACULTAD. @param P_JORNADA_FACULTAD VARCHAR2 => JORNADA FACULTAD. */ PROCEDURE GET_INDICADORES ( P_CODIGO_FACULTAD VARCHAR2, P_JORNADA_FACULTAD VARCHAR2 ) IS V_BODY JSON; V_ERROR JSON; V_HABEAS_DATA NUMBER; V_FORM1 NUMBER; V_FORM2 NUMBER; V_PAGO_INS NUMBER; V_ENTREVISTA NUMBER; V_ADMITIDO NUMBER; V_MATRICULADO NUMBER; V_ANIO VARCHAR2 (4); V_CICLO VARCHAR2 (2); V_ESQUEMA VARCHAR2 (32); BEGIN POSTGRADO.PKG_HTML.CORSHEADERS(); BEGIN SELECT ANIO, CICLO INTO V_ANIO, V_CICLO FROM POSTGRADO.A_ASPIRANTES WHERE CODIGO_FACULTAD = P_CODIGO_FACULTAD AND JORNADA_FACULTAD = P_JORNADA_FACULTAD AND ROWNUM = '1' ORDER BY TO_NUMBER(ANIO || CICLO) DESC; EXCEPTION WHEN OTHERS THEN ADMISIONES.PKG_UTILS.GETANIOCICLOESQUEMA ('2', V_ANIO, V_CICLO, V_ESQUEMA); END; V_BODY := JSON (); -- OBTENCION DE LOS INDICADORES. SELECT NVL(SUM(HABEAS_DATA), 0) HABEAS_DATA, NVL(SUM(FORM1), 0) FORM1, NVL(SUM(FORM2), 0) FORM2, NVL(SUM(PAGO_INS), 0) PAGO_INS, NVL(SUM(ENTREVISTA), 0) ENTREVISTA, NVL(SUM(ADMITIDO), 0) ADMITIDO, NVL(SUM(MATRICULADO), 0) MATRICULADO INTO V_HABEAS_DATA, V_FORM1, V_FORM2, V_PAGO_INS, V_ENTREVISTA, V_ADMITIDO, V_MATRICULADO FROM (-- PERSONAS INTERESADAS EN INGRESAR A ESTUDIOS QUE NO ESTAN EN A_ASPIRANTES. SELECT 1 AS HABEAS_DATA, 0 AS FORM1, 0 AS FORM2, 0 AS PAGO_INS, 0 as ENTREVISTA, 0 AS ADMITIDO, 0 AS MATRICULADO FROM DESARROLLOSPRE.CTI_INTERESADO I INNER JOIN ADMISIONES.A_FACULTADES F ON I.CODIGO_FACULTAD = F.CODIGO AND I.JORNADA_FACULTAD = F.JORNADA INNER JOIN DESARROLLOSPRE.CTI_CAMPANIA C ON I.ORIGEN = C.CODIGO WHERE I.ANIO = V_ANIO AND I.CICLO = V_CICLO AND F.CODIGO = P_CODIGO_FACULTAD AND F.JORNADA = P_JORNADA_FACULTAD -- QUE NO EXISTAN EN A_ASPIRANTES. AND NOT EXISTS(SELECT 1 FROM ADMISIONES.A_ASPIRANTES AA WHERE AA.NUMDOC = I.NUMDOC AND AA.TIPDOC = I.TIPDOC AND AA.ANIO = I.ANIO AND AA.CICLO = I.CICLO AND I.CODIGO_FACULTAD = AA.CODIGO_FACULTAD AND I.JORNADA_FACULTAD = AA.JORNADA_FACULTAD UNION SELECT 1 FROM POSTGRADO.A_ASPIRANTES AP WHERE AP.NUMDOC = I.NUMDOC AND AP.ANIO = I.ANIO AND AP.CICLO = I.CICLO AND I.CODIGO_FACULTAD = AP.CODIGO_FACULTAD AND I.JORNADA_FACULTAD = AP.JORNADA_FACULTAD) /*UNION ALL -- ASPIRANTES DE PREGRADO. SELECT 1 AS HABEAS_DATA, 1 AS FORM1, CASE WHEN A.NUMSNP IS NOT NULL THEN 1 ELSE 0 END AS FORM2, NVL((SELECT 1 FROM G_OTROS_PAGOS OP WHERE OP.CODIGO_EST = A.CODIGO AND OP.INDICADOR_PAGO = 'P' AND OP.ACTIVA = 1 AND OP.ANIO = A.ANIO AND OP.CICLO = A.CICLO), 0) AS PAGO_INS, CASE WHEN A.PENTRE IS NOT NULL THEN 1 ELSE 0 END AS ENTREVISTA, CASE WHEN A.IND1 = 1 THEN 0 WHEN A.IND1 = 2 THEN 1 ELSE NULL END AS ADMITIDO, NVL((SELECT 1 FROM B_ESTUDIANTES E WHERE E.CODIGO IS NOT NULL AND E.CODIGO = A.COD_DEF AND E.INDICADOR_PAGO IN ('P', 'V')), 0) AS MATRICULADO FROM A_ASPIRANTES A INNER JOIN A_FACULTADES F ON A.CODIGO_FACULTAD = F.CODIGO AND A.JORNADA_FACULTAD = F.JORNADA WHERE A.ANIO = '2019' AND A.CICLO = '02' AND F.CODIGO = P_CODIGO_FACULTAD AND F.JORNADA = P_JORNADA_FACULTAD*/ -- ASPIRANTES DE POSGRADO. UNION ALL SELECT 1 AS HABEAS_DATA, 1 AS FORM1, CASE WHEN A.SEXO IS NOT NULL THEN 1 ELSE 0 END AS FORM2, NVL((SELECT 1 FROM G_OTROS_PAGOS OP WHERE OP.CODIGO_EST = A.CODIGO AND OP.INDICADOR_PAGO = 'P' AND OP.ACTIVA = 1 AND OP.ANIO = A.ANIO AND OP.CICLO = A.CICLO), 0) AS PAGO_INS, 0 AS ENTREVISTA, CASE WHEN A.IND1 = 1 THEN 0 WHEN A.IND1 = 2 THEN 1 ELSE NULL END AS ADMITIDO, NVL((SELECT 1 FROM POSTGRADO.B_ESTUDIANTES E WHERE E.CODIGO IS NOT NULL AND E.CODIGO = A.COD_DEF AND E.INDICADOR_PAGO IN ('P','V')), 0) AS MATRICULADO FROM POSTGRADO.A_ASPIRANTES A INNER JOIN ADMISIONES.A_FACULTADES F ON A.CODIGO_FACULTAD = F.CODIGO AND A.JORNADA_FACULTAD = F.JORNADA WHERE A.ANIO = V_ANIO AND A.CICLO = V_CICLO AND F.CODIGO = P_CODIGO_FACULTAD AND F.JORNADA = P_JORNADA_FACULTAD) ASPIRANTES; JSON.PUT (V_BODY, 'habeasData', V_HABEAS_DATA); JSON.PUT (V_BODY, 'form1', V_FORM1); JSON.PUT (V_BODY, 'form2', V_FORM2); JSON.PUT (V_BODY, 'pagoInscripcion', V_PAGO_INS); JSON.PUT (V_BODY, 'entrevista', V_ENTREVISTA); JSON.PUT (V_BODY, 'admitido', V_ADMITIDO); JSON.PUT (V_BODY, 'matriculado', V_MATRICULADO); JSON.HTP (V_BODY); EXCEPTION WHEN OTHERS THEN V_ERROR := JSON (); JSON.PUT (V_ERROR, 'status', 'Error'); --JSON.PUT (V_ERROR, 'message', SQLCODE || ' --- ' || SUBSTR (SQLERRM, 1, 200)); JSON.HTP(V_ERROR); END GET_INDICADORES; /* OBTENER NUMERO DE ESTUDIANTES POR TIPO DE INGRESO, FILTRADOS POR PROGRAMA ACAD�MICO. @param P_CODIGO_FACULTAD VARCHAR2 => CODIGO FACULTAD. @param P_JORNADA_FACULTAD VARCHAR2 => JORNADA FACULTAD. */ PROCEDURE GET_ESTUDIANTES_TIPO_ING ( P_CODIGO_FACULTAD VARCHAR2, P_JORNADA_FACULTAD VARCHAR2 ) IS V_CHARTS JSON_LIST; V_CHART JSON; V_ITEMS JSON_LIST; V_ITEM JSON; V_ERROR JSON; V_REGISTRO JSON; V_VALUE NUMBER; BEGIN POSTGRADO.PKG_HTML.CORSHEADERS(); V_CHARTS := JSON_LIST(); -- PRIMERA GRAFICA. V_CHART := JSON(); JSON.PUT (V_CHART, 'label', 'Tipo de Estudiante'); JSON.PUT (V_CHART, 'xAxisLabel', 'Tipo de Estudiante'); JSON.PUT (V_CHART, 'yAxisLabel', 'Cantidad de estudiantes'); V_ITEMS := JSON_LIST(); -- ITERANDO SOBRE RESULTADOS DE BUSQUEDA. FOR AUXILIAR_RECORD IN (SELECT TIPO_DE_INGRESO, TIPO_DE_INGRESO_LABEL, COUNT(CODIGO) NUMERO_DE_ESTUDIANTES FROM (SELECT CASE WHEN (E.CICLO_DE_INGRESO = E.ANIO || TO_NUMBER(E.CICLO)) THEN E.TIPO_DE_INGRESO ELSE 'AN' END TIPO_DE_INGRESO, CASE WHEN (E.CICLO_DE_INGRESO = E.ANIO || TO_NUMBER(E.CICLO)) THEN TE.DESCRIPCION ELSE 'ANTIGUO' END TIPO_DE_INGRESO_LABEL, E.CODIGO FROM POSTGRADO.B_ESTUDIANTES E LEFT JOIN ADMISIONES.A_TIPO_ESTUDIANTE TE ON TE.TIPO = E.TIPO_DE_INGRESO WHERE INDICADOR_PAGO IN ('P', 'V', 'W') AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD) B GROUP BY TIPO_DE_INGRESO, TIPO_DE_INGRESO_LABEL) LOOP V_ITEM := JSON(); JSON.PUT (V_ITEM, 'key', AUXILIAR_RECORD.TIPO_DE_INGRESO); JSON.PUT (V_ITEM, 'label', AUXILIAR_RECORD.TIPO_DE_INGRESO_LABEL); JSON.PUT (V_ITEM, 'value', AUXILIAR_RECORD.NUMERO_DE_ESTUDIANTES); JSON_LIST.APPEND (V_ITEMS, V_ITEM.TO_JSON_VALUE); END LOOP; JSON.PUT (V_CHART, 'barChartItems', V_ITEMS); JSON_LIST.APPEND (V_CHARTS, V_CHART.TO_JSON_VALUE); -- SEGUNDA GRAFICA. V_CHART := JSON(); JSON.PUT (V_CHART, 'label', 'Género'); JSON.PUT (V_CHART, 'xAxisLabel', 'Género'); JSON.PUT (V_CHART, 'yAxisLabel', 'Cantidad de estudiantes'); V_ITEMS := JSON_LIST(); -- ITERANDO SOBRE RESULTADOS DE BUSQUEDA. FOR AUXILIAR_RECORD IN (SELECT SEXO, COUNT(E.CODIGO) NUMERO_DE_ESTUDIANTES FROM POSTGRADO.B_ESTUDIANTES E WHERE INDICADOR_PAGO IN ('P', 'V', 'W') AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD GROUP BY SEXO) LOOP V_ITEM := JSON(); JSON.PUT (V_ITEM, 'key', AUXILIAR_RECORD.SEXO); JSON.PUT (V_ITEM, 'label', AUXILIAR_RECORD.SEXO); JSON.PUT (V_ITEM, 'value', AUXILIAR_RECORD.NUMERO_DE_ESTUDIANTES); JSON_LIST.APPEND (V_ITEMS, V_ITEM.TO_JSON_VALUE); END LOOP; JSON.PUT (V_CHART, 'barChartItems', V_ITEMS); JSON_LIST.APPEND (V_CHARTS, V_CHART.TO_JSON_VALUE); -- TERCERA GRAFICA. V_CHART := JSON(); JSON.PUT (V_CHART, 'label', 'Tipo de Matricula'); JSON.PUT (V_CHART, 'xAxisLabel', 'Tipo de Matricula'); JSON.PUT (V_CHART, 'yAxisLabel', 'Cantidad de estudiantes'); V_ITEMS := JSON_LIST(); -- ITERANDO SOBRE RESULTADOS DE BUSQUEDA. FOR AUXILIAR_RECORD IN (SELECT P.INDICADOR_PAGO, P.PERIODO, COUNT(E.CODIGO) NUMERO_DE_ESTUDIANTES FROM POSTGRADO.B_ESTUDIANTES E INNER JOIN POSTGRADO.CTI_PERIODO P ON E.INDICADOR_PAGO = P.INDICADOR_PAGO WHERE E.INDICADOR_PAGO IN ('P', 'V', 'W') AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD GROUP BY P.INDICADOR_PAGO, P.PERIODO) LOOP V_ITEM := JSON(); JSON.PUT (V_ITEM, 'key', AUXILIAR_RECORD.INDICADOR_PAGO); JSON.PUT (V_ITEM, 'label', AUXILIAR_RECORD.PERIODO); JSON.PUT (V_ITEM, 'value', AUXILIAR_RECORD.NUMERO_DE_ESTUDIANTES); JSON_LIST.APPEND (V_ITEMS, V_ITEM.TO_JSON_VALUE); END LOOP; JSON.PUT (V_CHART, 'barChartItems', V_ITEMS); JSON_LIST.APPEND (V_CHARTS, V_CHART.TO_JSON_VALUE); -- CUARTA GRAFICA. V_CHART := JSON(); JSON.PUT (V_CHART, 'label', 'Plan de estudio'); JSON.PUT (V_CHART, 'xAxisLabel', 'Plan de estudio'); JSON.PUT (V_CHART, 'yAxisLabel', 'Cantidad de estudiantes'); V_ITEMS := JSON_LIST(); -- ITERANDO SOBRE RESULTADOS DE BUSQUEDA. FOR AUXILIAR_RECORD IN (SELECT P.PLAN_ESTUDIO, P.DESCRIPCION, COUNT(E.CODIGO) NUMERO_DE_ESTUDIANTES FROM POSTGRADO.A_PLANES_DE_ESTUDIO P INNER JOIN POSTGRADO.B_ESTUDIANTES E ON E.CODIGO_FACULTAD = P.CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P.JORNADA_FACULTAD AND E.PLAN_ESTUDIO = P.PLAN_ESTUDIO WHERE E.INDICADOR_PAGO IN ('P', 'V', 'W') AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD GROUP BY P.PLAN_ESTUDIO, P.DESCRIPCION) LOOP V_ITEM := JSON(); JSON.PUT (V_ITEM, 'key', AUXILIAR_RECORD.PLAN_ESTUDIO); JSON.PUT (V_ITEM, 'label', AUXILIAR_RECORD.DESCRIPCION); JSON.PUT (V_ITEM, 'value', AUXILIAR_RECORD.NUMERO_DE_ESTUDIANTES); JSON_LIST.APPEND (V_ITEMS, V_ITEM.TO_JSON_VALUE); END LOOP; JSON.PUT (V_CHART, 'barChartItems', V_ITEMS); JSON_LIST.APPEND (V_CHARTS, V_CHART.TO_JSON_VALUE); -- IMPRESION JSON. JSON_LIST.HTP(V_CHARTS, FALSE); EXCEPTION WHEN OTHERS THEN V_ERROR := JSON (); JSON.PUT (V_ERROR, 'status', 'Error'); JSON.PUT (V_ERROR, 'message', SQLCODE || ' --- ' || SUBSTR (SQLERRM, 1, 200)); JSON.HTP(V_ERROR); END GET_ESTUDIANTES_TIPO_ING; PROCEDURE GET_DETALLES_EST_TIPO_ING ( P_CODIGO_FACULTAD VARCHAR2, P_JORNADA_FACULTAD VARCHAR2 ) IS V_ESTUDIANTES JSON_LIST; V_ESTUDIANTE JSON; V_ERROR JSON; v_periodo varchar2(100) default null; --mariano rua mejia 11/08/2020 BEGIN V_ESTUDIANTES := JSON_LIST(); select unique b.anio||b.ciclo --mariano rua mejia 11/08/2020 into v_periodo from b_estudiantes b; -- ITERANDO SOBRE RESULTADOS DE BUSQUEDA. FOR AUXILIAR_RECORD IN ( SELECT E.CODIGO, E.NOMBRE, NVL(BG.TOPE, 0) TOPE, NVL(BG.TOPE, 0) - NVL(BG.DISPONIBLES, 0) INSCRITOS, NVL(CE.CREDITOS, 0) ADICIONALES FROM POSTGRADO.B_ESTUDIANTES E LEFT JOIN POSTGRADO.CTI_BOLSA_GENERAL BG ON BG.CODIGO = E.CODIGO and bg.anio||bg.ciclo = e.anio||e.ciclo --mariano rua mejia 11/08/2020 LEFT JOIN (SELECT SUM(NUMERO_CREDITOS_ADICIONALES) CREDITOS, CEA.CODIGO_ESTUDIANTE FROM CTI_CRED_EXTRAS_AUTORIZACION CEA INNER JOIN ADMISIONES.G_GUIAS_DE_PAGO GDP ON GDP.CODIGO_GUIA = CEA.CODIGO_GUIA WHERE GDP.INDICADOR_PAGO = 'P' GROUP BY CEA.CODIGO_ESTUDIANTE) CE ON CE.CODIGO_ESTUDIANTE = E.CODIGO WHERE E.INDICADOR_PAGO IN ('P', 'V', 'W') AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD AND E.ANIO||E.CICLO = V_PERIODO --mariano rua mejia 11/08/2020 ORDER BY E.CODIGO) LOOP V_ESTUDIANTE := JSON(); JSON.PUT (V_ESTUDIANTE, 'codigo', AUXILIAR_RECORD.CODIGO); JSON.PUT (V_ESTUDIANTE, 'nombre', AUXILIAR_RECORD.NOMBRE); JSON.PUT (V_ESTUDIANTE, 'creditosMatriculados', AUXILIAR_RECORD.TOPE); JSON.PUT (V_ESTUDIANTE, 'creditosInscritos', AUXILIAR_RECORD.INSCRITOS); JSON.PUT (V_ESTUDIANTE, 'estado', CASE WHEN AUXILIAR_RECORD.TOPE = AUXILIAR_RECORD.INSCRITOS THEN 'Completo' ELSE 'Incompleto' END); JSON.PUT (V_ESTUDIANTE, 'creditosAdicionales', AUXILIAR_RECORD.ADICIONALES); JSON_LIST.APPEND (V_ESTUDIANTES, V_ESTUDIANTE.TO_JSON_VALUE); END LOOP; JSON_LIST.HTP(V_ESTUDIANTES, FALSE); EXCEPTION WHEN OTHERS THEN V_ERROR := JSON (); JSON.PUT (V_ERROR, 'status', 'Error'); JSON.PUT (V_ERROR, 'message', SQLCODE || ' --- ' || SUBSTR (SQLERRM, 1, 200)); JSON.HTP(V_ERROR); END GET_DETALLES_EST_TIPO_ING; /* OBTIENE EL ESTADO DE LAS NOTAS PARA EL PERIODO ACTUAL. @param P_CODIGO_FACULTAD VARCHAR2 => CODIGO FACULTAD. */ PROCEDURE GET_ESTADO_NOTAS ( P_CODIGO_FACULTAD VARCHAR2 ) IS V_BODY JSON; V_ERROR JSON; TYPE TYP_REF_CUR IS REF CURSOR; TYPE TYPE_PROF IS RECORD ( NOMPRO VARCHAR2(1000), APEDOC VARCHAR2(1000), NOMBRE VARCHAR2(1000) ); TYPE TYPE_HORARIO IS RECORD ( CODIGO_FACULTAD VARCHAR2(1000), JORNADA_FACULTAD VARCHAR2(1000), CODIGO_MATERIA VARCHAR2(1000), GRUPO_MATERIA VARCHAR2(1000), NOMBRE_PROFESOR VARCHAR2(1000), LUNES VARCHAR2(1000), MARTES VARCHAR2(1000), MIERCOLES VARCHAR2(1000), JUEVES VARCHAR2(1000), VIERNES VARCHAR2(1000), SABADO VARCHAR2(1000), CUPO VARCHAR2(1000), PROFESOR_PRACTICA VARCHAR2(1000), TEORIA_INTEGRADA VARCHAR2(1000), FACINT VARCHAR2(1000), CODMATINT VARCHAR2(1000), GRUPINT VARCHAR2(1000), CUPO_UTILIZADO VARCHAR2(1000), MATRICULADOS VARCHAR2(1000), ABIERTO VARCHAR2(1000), TIPO_MATERIA VARCHAR2(1000), NUMERO_DOCUMENTO VARCHAR2(1000), APEDOC VARCHAR2(1000), NOMBRE VARCHAR2(1000), POR_TEORIA VARCHAR2(1000), POR_PRACTICA VARCHAR2(1000), SEDE VARCHAR2(1000), ANIO VARCHAR2(1000), CICLO VARCHAR2(1000), FECHA_INICIO_CLASES VARCHAR2(1000), FECHA_INICIO_NOTAS VARCHAR2(1000), FECHA_FIN_NOTAS VARCHAR2(1000), SEMANAS VARCHAR2(1000), PLAN_ESTUDIO VARCHAR2(1000), NOMBRE_MATERIA VARCHAR2(1000), INTENSIDAD_HORARIA VARCHAR2(1000), SEMESTRE VARCHAR2(1000), CREDITOS VARCHAR2(1000), ABREVIATURA_NOMBRE VARCHAR2(1000), AREA VARCHAR2(1000), HOR_TRABAJO_INDEPENDIENTE VARCHAR2(1000), PLAN_CARACTER VARCHAR2(1000), CONSECUTIVO VARCHAR2(1000), GRAN_FACULTAD VARCHAR2(1000), FECHA_FIN_CLASES VARCHAR2(1000), FECHA VARCHAR2(1000), NUMERO_DOCUMENTO2 VARCHAR2(1000), INDICADOR_CIERRE VARCHAR2(1000), APROBARON_DEF VARCHAR2(1000), REPROBARON_DEF VARCHAR2(1000), POR_APROBARON_DEF VARCHAR2(1000), POR_REPROBARON_DEF VARCHAR2(1000), FECHA_EXAMEN_FINAL VARCHAR2(1000), FECHA_TERCER_INGRESO VARCHAR2(1000) ); V_REF_CUR TYP_REF_CUR; V_REF_CUR2 TYP_REF_CUR; V_PROFE TYPE_PROF; V_DATOS TYPE_HORARIO; V_MATRICULADOS NUMBER DEFAULT 0; V_MATRICULADOS_TOTALES NUMBER DEFAULT 0; V_APROBADOS_TOTALES NUMBER DEFAULT 0; V_REPROBADOS_TOTALES NUMBER DEFAULT 0; BEGIN POSTGRADO.PKG_HTML.CORSHEADERS(); V_BODY := JSON(); -- OBTENCION DE TODOS LOS DOCENTES POR FACULTAD E ITERACION SOBRE ELLOS. V_REF_CUR := POSTGRADO.PKG_NOTAS.PRC_GET_DOCENTES_CURSOR (P_CODIGO_FACULTAD); LOOP FETCH V_REF_CUR INTO V_PROFE; EXIT WHEN V_REF_CUR%NOTFOUND; -- OBTENCION DE TODOS LOS CURSOS POR DOCENTE E ITERACION SOBRE ELLOS. V_REF_CUR2 := POSTGRADO.PKG_NOTAS.PRC_GET_HORARIOS_CURSOR(P_CODIGO_FACULTAD, V_PROFE.APEDOC, V_PROFE.NOMBRE); LOOP FETCH V_REF_CUR2 INTO V_DATOS; EXIT WHEN V_REF_CUR2%NOTFOUND; -- OBTENCION DE NUMERO DE MATRICULADOS POR CURSO SELECT COUNT (*) INTO V_MATRICULADOS FROM B_PREMATRICULA_NOTAS_DEPURADA INS WHERE INS.FACULTAD_CURSAR = V_DATOS.CODIGO_FACULTAD AND INS.MATERIA_CURSAR = V_DATOS.CODIGO_MATERIA AND TO_NUMBER (INS.GRUPO) = TO_NUMBER (V_DATOS.GRUPO_MATERIA) AND INS.INDICADOR_PAGO IN ('P', 'V', 'C'); -- SUMA DE ACUMULADOS. V_MATRICULADOS_TOTALES := V_MATRICULADOS_TOTALES + V_MATRICULADOS; V_APROBADOS_TOTALES := V_APROBADOS_TOTALES + NVL(V_DATOS.APROBARON_DEF, '0'); V_REPROBADOS_TOTALES := V_REPROBADOS_TOTALES + NVL(V_DATOS.REPROBARON_DEF, '0'); END LOOP; END LOOP; JSON.PUT(V_BODY, 'estudiantesMatriculados', V_MATRICULADOS_TOTALES); JSON.PUT(V_BODY, 'estudiantesMatriculadosConNota', V_APROBADOS_TOTALES + V_REPROBADOS_TOTALES); JSON.PUT(V_BODY, 'estudiantesMatriculadosSinNota', V_MATRICULADOS_TOTALES - (V_APROBADOS_TOTALES + V_REPROBADOS_TOTALES)); JSON.PUT(V_BODY, 'estudiantesAprobados', V_APROBADOS_TOTALES); JSON.PUT(V_BODY, 'estudiantesReprobados', V_REPROBADOS_TOTALES); JSON.HTP(V_BODY); EXCEPTION WHEN OTHERS THEN V_ERROR := JSON (); JSON.PUT (V_ERROR, 'status', 'Error'); JSON.PUT (V_ERROR, 'message', SQLCODE || ' --- ' || SUBSTR (SQLERRM, 1, 200)); JSON.HTP(V_ERROR); END GET_ESTADO_NOTAS; /* OBTIENE DATOS ESTADISTICOS DE LAS NOTAS PARA EL PERIODO ACTUAL (DATOS DESTINADOS PARA SER UTILIZADOS EN GRAFICA DE CAJA Y BIGOTES): - CUARTILES 1, 2(MEDIANA) Y 3. - MEDIA. - VALORES MAXIMOS Y MINIMOS. - OUTLIERS. @param P_CODIGO_FACULTAD VARCHAR2 @param P_JORNADA_FACULTAD VARCHAR2 */ PROCEDURE GET_ESTADISTICAS_NOTAS ( P_CODIGO_FACULTAD VARCHAR2, P_JORNADA_FACULTAD VARCHAR2 ) IS V_BODY JSON_LIST; V_ERROR JSON; V_DATA_SET TABLE_DATA_SET; BEGIN POSTGRADO.PKG_HTML.CORSHEADERS(); V_BODY := JSON_LIST(); -- OBTENIENDO PRIMER DATA SET. SELECT REGISTRO_DATA_ITEM(PND.DEFINITIVA) BULK COLLECT INTO V_DATA_SET FROM POSTGRADO.B_PREMATRICULA_NOTAS_DEPURADA PND INNER JOIN POSTGRADO.B_ESTUDIANTES E ON E.CODIGO = PND.CODIGO_ESTUDIANTE WHERE PND.DEFINITIVA IS NOT NULL; JSON_LIST.APPEND (V_BODY, GET_ESTADISTICAS_DATA_SET('Total universidad', V_DATA_SET).TO_JSON_VALUE); -- OBTENIENDO SEGUNDO DATA SET. SELECT REGISTRO_DATA_ITEM(PND.DEFINITIVA) BULK COLLECT INTO V_DATA_SET FROM POSTGRADO.B_PREMATRICULA_NOTAS_DEPURADA PND INNER JOIN POSTGRADO.B_ESTUDIANTES E ON E.CODIGO = PND.CODIGO_ESTUDIANTE WHERE PND.DEFINITIVA IS NOT NULL AND E.CODIGO_FACULTAD = P_CODIGO_FACULTAD AND E.JORNADA_FACULTAD = P_JORNADA_FACULTAD; JSON_LIST.APPEND (V_BODY, GET_ESTADISTICAS_DATA_SET('Total programa', V_DATA_SET).TO_JSON_VALUE); JSON_LIST.HTP(V_BODY, FALSE); EXCEPTION WHEN OTHERS THEN V_ERROR := JSON (); JSON.PUT (V_ERROR, 'status', 'Error'); JSON.PUT (V_ERROR, 'message', SQLCODE || ' --- ' || SUBSTR (SQLERRM, 1, 200)); JSON.HTP(V_ERROR); END GET_ESTADISTICAS_NOTAS; /* OBTIENE DATOS ESTADISTICOS DE UN DATA SET - CUARTILES 1, 2(MEDIANA) Y 3. - MEDIA. - VALORES MAXIMOS Y MINIMOS. - OUTLIERS. @param P_NOMBRE_DATA_SET VARCHAR => Nombre del Data Set. @param P_DATA_SET TABLE_DATA_SET => Valores del Data Set. @return */ FUNCTION GET_ESTADISTICAS_DATA_SET( P_NOMBRE_DATA_SET VARCHAR, P_DATA_SET TABLE_DATA_SET ) RETURN JSON IS V_BODY JSON; V_ERROR JSON; V_OUTLIERS JSON_LIST; V_LIMITE_INFERIOR_OUTLIER NUMBER; V_MINIMO NUMBER; V_PRIMER_CUARTIL NUMBER; V_MEDIANA NUMBER; V_TERCER_CUARTIL NUMBER; V_MAXIMO NUMBER; V_LIMITE_SUPERIOR_OUTLIER NUMBER; V_MEDIA NUMBER; BEGIN V_BODY := JSON(); V_OUTLIERS := JSON_LIST(); -- CALCULO DE MINIMOS Y MAXIMOS DE OUTLIERS, CUARTILES, MEDIANA Y MEDIA. SELECT PRIMER_CUARTIL - 1.5 * (TERCER_CUARTIL - PRIMER_CUARTIL) LIMITE_INFERIOR_OUTLIER, PRIMER_CUARTIL, SEGUNDO_CUARTIL, TERCER_CUARTIL, TERCER_CUARTIL + 1.5 * (TERCER_CUARTIL - PRIMER_CUARTIL) LIMITE_SUPERIOR_OUTLIER, MEDIA INTO V_LIMITE_INFERIOR_OUTLIER, V_PRIMER_CUARTIL, V_MEDIANA, V_TERCER_CUARTIL, V_LIMITE_SUPERIOR_OUTLIER, V_MEDIA FROM (SELECT MEDIAN (CASE WHEN VALOR < MEDIANA THEN VALOR END) PRIMER_CUARTIL, MEDIANA SEGUNDO_CUARTIL, MEDIAN (CASE WHEN VALOR > MEDIANA THEN VALOR END) TERCER_CUARTIL, AVG(VALOR) MEDIA FROM (SELECT VALOR, MEDIAN(VALOR) OVER () MEDIANA FROM TABLE(P_DATA_SET)) GROUP BY MEDIANA); -- CALCULANDO VALOR MINIMO QUE NO SEA CONSIDERADO UN OUTLIER. SELECT MIN(VALOR) INTO V_MINIMO FROM TABLE(P_DATA_SET) WHERE VALOR >= V_LIMITE_INFERIOR_OUTLIER AND VALOR IS NOT NULL; -- CALCULANDO VALOR MAXIMO QUE NO SEA CONSIDERADO UN OUTLIER. SELECT MAX(VALOR) INTO V_MAXIMO FROM TABLE(P_DATA_SET) WHERE VALOR <= V_LIMITE_SUPERIOR_OUTLIER AND VALOR IS NOT NULL; -- ENCONTRANDO LOS OUTLIERS TANTO INFERIORES COMO SUPERIORES. FOR OUTLIER IN (SELECT VALOR FROM TABLE(P_DATA_SET) WHERE VALOR IS NOT NULL AND ( VALOR < V_LIMITE_INFERIOR_OUTLIER OR VALOR > V_LIMITE_SUPERIOR_OUTLIER)) LOOP -- AGREGAMOS OUTLIER A LA LISTA. JSON_LIST.APPEND (V_OUTLIERS, OUTLIER.VALOR); END LOOP; JSON.PUT(V_BODY, 'nombreDataSet', P_NOMBRE_DATA_SET); JSON.PUT(V_BODY, 'valorMinimo', V_MINIMO); JSON.PUT(V_BODY, 'primerCuartil', V_PRIMER_CUARTIL); JSON.PUT(V_BODY, 'mediana', V_MEDIANA); JSON.PUT(V_BODY, 'tercerCuartil', V_TERCER_CUARTIL); JSON.PUT(V_BODY, 'valorMaximo', V_MAXIMO); JSON.PUT(V_BODY, 'outliers', V_OUTLIERS); RETURN V_BODY; EXCEPTION WHEN OTHERS THEN V_ERROR := JSON (); JSON.PUT (V_ERROR, 'status', 'Error'); JSON.PUT (V_ERROR, 'message', SQLCODE || ' --- ' || SUBSTR (SQLERRM, 1, 200)); RETURN V_ERROR; END GET_ESTADISTICAS_DATA_SET; END PKG_CTI_DASHBOARD_POSGRADOS;
true
4f25e8d66a97b19cc712d732ddd445821748546e
SQL
ndxt/centit-workflow
/centit-workflow-module/src/sqlScript/版本升级和变更/update20200907.sql
UTF-8
1,601
3.46875
3
[]
no_license
-- 将版本号升级到4.7 修改 -- WF_FLOW_TEAM_ROLE 修改这表为 WF_OPT_TEAM_ROLE -- 可以新建这个表, 数据库中的表可以不动,代码中废弃这个表 drop table if exists WF_OPT_TEAM_ROLE; create table WF_OPT_TEAM_ROLE ( OPT_TEAM_ROLE_ID varchar(32) comment '主键id', OPT_ID varchar(32) comment '关联的流程业务id', ROLE_CODE varchar(100) comment '办件角色code', ROLE_NAME varchar(100) comment '办件角色名称', FORMULA_CODE varchar(100) comment '办件角色的约束范围', TEAM_ROLE_ORDER numeric(4,0) DEFAULT NULL comment '办件角色排序', MODIFY_TIME datetime NOT NULL DEFAULT CURRENT_TIMESTAMP comment '修改时间', primary key (OPT_TEAM_ROLE_ID) ); -- WF_FLOW_VARIABLE_DEFINE 修改这表为 WF_OPT_VARIABLE_DEFINE -- 同样可以新建这个表, 数据库中的表可以不动,代码中废弃这个表 drop table if exists WF_OPT_VARIABLE_DEFINE; create table WF_OPT_VARIABLE_DEFINE ( OPT_VARIABLE_ID varchar(32) comment '主键id', OPT_ID varchar(32) comment '关联的流程业务id', VARIABLE_NAME varchar(100) comment '变量名', VARIABLE_DESC varchar(100) comment '变量中文描述', VARIABLE_TYPE varchar(100) comment '变量类型:E:集合 S:单值', DEFAULT_VALUE varchar(256) comment '变量默认值', MODIFY_TIME datetime NOT NULL DEFAULT CURRENT_TIMESTAMP comment '修改时间', primary key (OPT_VARIABLE_ID) ); -- 流程阶段添加排序字段STAGE_ORDER alter table WF_FLOW_STAGE add STAGE_ORDER numeric(4,0);
true
5f48bc35802573b9478ea4d726726991af7bcadd
SQL
yuhsuanh/RelationalDatabase
/assignment1a/Assignment1a Yu-hsuan Huang_Misha Wali_v2.sql
UTF-8
5,399
3.890625
4
[]
no_license
/* Author: 200443723 - Yu-Hsuan Huang 200443124 - Misha Wali Date: May 29th, 2020 Topic: Assignment 1a - Class registration Description: 1. Create and drop database (if exists / if not exists) 2. Create table 3. Display structure of the table 4. Insert records in different ways 5. Display all records in the table */ # a) Drop a database if it exists DROP DATABASE IF EXISTS georgian_college; # a) create a database by the same name and use it. CREATE DATABASE georgian_college; #Use database USE georgian_college; /* b) Create a table therein that stores relevant information about an entity of your choice Choose relevant fields of BEST FIT to store data pertaining to that entity. Comment the purpose of each field. Ensure that the table has at least: i. a primary key field ii. a field of type varchar iii. a field of type char iv. a field of type float or double, unsigned v. a field of type smallint, unsigned vi. a field of enumerated data type vii. a field of date data type viii. at least one field that cannot contain a null value ix. at least one field has a relevant default value */ CREATE TABLE class_registration ( course_crn SMALLINT UNSIGNED PRIMARY KEY, -- from 0 to 65535 (AUTO_INCREMENT) course_code CHAR(4) NOT NULL, course_number CHAR(4) NOT NULL, -- from 0 to 65535 course_title VARCHAR(100) NOT NULL, campus VARCHAR(20) DEFAULT 'Barrie', credits TINYINT UNSIGNED, day_of_week ENUM('Mon', 'Tues', 'Wed', 'Thur', 'Fri'), time_of_day VARCHAR(50), date_of_start DATE, date_of_end DATE, classroom CHAR(10) NOT NULL, instructor_name VARCHAR(50) NOT NULL ); # c) Display the structure of the table DESC class_registration; # d) Populate the table with relevant data, at least 10 records. Text/string data in quotes and numeric without quotes please. # Record 1. INSERT INTO class_registration VALUE (30786, 'COMP', '2003', 'Relational Database', 'Barrie', 3.000, 'Fri', '11:00 am - 1:50 pm', '2020-05-22', '2020-08-07', 'K-324', 'Anju K. Chawla'); # Record 2. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, instructor_name) VALUE (30730, 'COMM', '1017', 'Work Environment Comm', 'Tracey A. Bedford'); # Record 3. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, credits, instructor_name) VALUE (30782, 'COMP', '1098', '.NET Programming using C#', DEFAULT, 3.000, 'Tracey A. Bedford'); # Record 4. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, credits, day_of_week, time_of_day, instructor_name) VALUE (31006, 'ENTR', '1002', 'Intro to Entrepreneurship', DEFAULT, 3.000, 'Tues', '8:00 am - 10:50 am', 'John Pickard'); # Record 5. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, credits, day_of_week, time_of_day, date_of_start, date_of_end, instructor_name) VALUE (30746, 'COMP', '1008', 'Intro Obj Oriented Prog-Java', DEFAULT, 3.000, 'Wed', '10:00 am - 12:50 pm', '2020-05-20', '2020-08-05', 'Radhika Sharma'); # Record 6. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, credits, day_of_week, time_of_day, date_of_start, date_of_end, classroom, instructor_name) VALUE (30743, 'COMP', '1006', 'Intro to Web Prog using PHP', 'Barrie', 3.000, 'Thur', '11:00 am - 1:50 pm', '2020-05-21', '2020-08-06', 'Online', 'Albert Villaruz'); # Record 7. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, credits, day_of_week, time_of_day, date_of_start, date_of_end, classroom, instructor_name) VALUE (23370, 'COMP', '1035', 'Networking Essentials', DEFAULT, NULL, NULL, NULL, NULL, NULL, 'E-002', 'Ali Ershad-Manesh'); # Record 8. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, credits, day_of_week, time_of_day, classroom, instructor_name) VALUE (23373, 'CPHR', '0001', 'Co-op and Career Preparation', DEFAULT, 0.000, 'Tues', NULL, 'A-119', 'Beth Salt'); # Record 9. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, classroom, instructor_name) VALUE (23372, 'MATH', '1003', 'Math for the Computer Industry', 'Barrie', 'H-113', 'Linda S. Kettle'); # Record 10. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, credits, classroom, instructor_name) VALUE (23369, 'COMP', '1030', 'Programming Fundamentals', DEFAULT, 3.00, NULL,'Wayne Brown'); # Record 11. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, day_of_week, time_of_day, date_of_start, date_of_end, classroom, instructor_name) VALUE (21148, 'COMM', '1016', 'Communication Essentials', NULL, NULL, NULL, NULL, 'K-219', 'Lori E. Hallahan'); # Record 12. INSERT INTO class_registration (course_crn, course_code, course_number, course_title, campus, credits, day_of_week, time_of_day, date_of_start, date_of_end, classroom, instructor_name) VALUE (23371, 'COMP', '1045', 'Internet of Things - Arduino', DEFAULT, 3.000, 'Thur', '11:00 am - 1:50 pm', NULL, NULL, 'K-324','Matthew Wilson'); # Record 13. INSERT INTO class_registration VALUE (23368, 'COMP', '1002', 'HTML, CSS, & JS Fund.', DEFAULT, 3.000, 'Fri', '11:00 am - 1:50 pm', '2020-01-10', '2020-04-17', 'A-224', 'Julie-Ann C. Snache'); # e) Add a SELECT statement to display the data in the table. SELECT * FROM class_registration ORDER BY course_crn ASC;
true
21d79ae53ae4760d185ddec13e8e94dc2f5be666
SQL
flavio022/spring_restApi
/create.sql
UTF-8
97,556
3.765625
4
[]
no_license
create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table cidade ( id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id) ); create table cliente ( id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id) ); create table endereco ( id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id) ); create table estado ( id int4 generated by default as identity, nome varchar(255), primary key (id) ); create table item_pedido ( desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id) ); create table pagamento ( pedido_id int4 not null, estado int4, primary key (pedido_id) ); create table pagamento_com_boleto ( data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id) ); create table pagamento_com_cartao ( numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id) ); create table pedido ( id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id) ); create table produto ( id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id) ); create table produto_categoria ( produto_id int4 not null, categoria_id int4 not null ); create table telefone ( cliente_id int4 not null, telefones varchar(255) ); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente; create table categoria (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table cidade (id int4 generated by default as identity, nome varchar(255), estado_id int4, primary key (id)); create table cliente (id int4 generated by default as identity, cpf_ou_cnpj varchar(255), email varchar(255), nome varchar(255), senha varchar(255), tipo int4, primary key (id)); create table endereco (id int4 generated by default as identity, bairro varchar(255), cep varchar(255), complemento varchar(255), logradouro varchar(255), numero varchar(255), cidade_id int4, cliente_id int4, primary key (id)); create table estado (id int4 generated by default as identity, nome varchar(255), primary key (id)); create table item_pedido (desconto float8, preco float8, quantidade int4, pedido_id int4 not null, produto_id int4 not null, primary key (pedido_id, produto_id)); create table pagamento (pedido_id int4 not null, estado int4, primary key (pedido_id)); create table pagamento_com_boleto (data_pagamento timestamp, data_vencimento timestamp, pedido_id int4 not null, primary key (pedido_id)); create table pagamento_com_cartao (numero_de_parcelas int4, pedido_id int4 not null, primary key (pedido_id)); create table pedido (id int4 generated by default as identity, instante timestamp, cliente_id int4, endereco_de_entrega_id int4, primary key (id)); create table produto (id int4 generated by default as identity, nome varchar(255), preco float8, primary key (id)); create table produto_categoria (produto_id int4 not null, categoria_id int4 not null); create table telefone (cliente_id int4 not null, telefones varchar(255)); alter table if exists cliente add constraint UK_cmxo70m08n43599l3h0h07cc6 unique (email); alter table if exists cidade add constraint FKkworrwk40xj58kevvh3evi500 foreign key (estado_id) references estado; alter table if exists endereco add constraint FK8b1kcb3wucapb8dejshyn5fsx foreign key (cidade_id) references cidade; alter table if exists endereco add constraint FK8s7ivtl4foyhrfam9xqom73n9 foreign key (cliente_id) references cliente; alter table if exists item_pedido add constraint FK60ym08cfoysa17wrn1swyiuda foreign key (pedido_id) references pedido; alter table if exists item_pedido add constraint FKtk55mn6d6bvl5h0no5uagi3sf foreign key (produto_id) references produto; alter table if exists pagamento add constraint FKthad9tkw4188hb3qo1lm5ueb0 foreign key (pedido_id) references pedido; alter table if exists pagamento_com_boleto add constraint FKcr74vrxf8nfph0knq2bho8doo foreign key (pedido_id) references pagamento; alter table if exists pagamento_com_cartao add constraint FKta3cdnuuxclwfh52t4qi432ow foreign key (pedido_id) references pagamento; alter table if exists pedido add constraint FK30s8j2ktpay6of18lbyqn3632 foreign key (cliente_id) references cliente; alter table if exists pedido add constraint FK1fihyy2fnocpuwc74674qmfkv foreign key (endereco_de_entrega_id) references endereco; alter table if exists produto_categoria add constraint FKq3g33tp7xk2juh53fbw6y4y57 foreign key (categoria_id) references categoria; alter table if exists produto_categoria add constraint FK1c0y58d3n6x3m6euv2j3h64vt foreign key (produto_id) references produto; alter table if exists telefone add constraint FK8aafha0njkoyoe3kvrwsy3g8u foreign key (cliente_id) references cliente;
true
b66208b851e3eb753f53968d6ef1ae0ca0583b5e
SQL
plopez145780/ifrocean
/doc/projet_ifrocean_presentation.sql
UTF-8
4,527
3.328125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.2 -- http://www.phpmyadmin.net -- -- Client : 127.0.0.1 -- Généré le : Lun 25 Juillet 2016 à 13:29 -- Version du serveur : 5.7.9 -- Version de PHP : 5.6.16 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 */; -- -- Base de données : `projet_ifrocean` -- -- -------------------------------------------------------- -- -- Structure de la table `especes` -- DROP TABLE IF EXISTS `especes`; CREATE TABLE IF NOT EXISTS `especes` ( `idEspece` int(11) NOT NULL AUTO_INCREMENT, `nomEspece` varchar(50) NOT NULL, PRIMARY KEY (`idEspece`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1; -- -- Contenu de la table `especes` -- INSERT INTO `especes` (`idEspece`, `nomEspece`) VALUES (1, 'Spirobranchus giganteus'), (2, 'Haemopis sanguisuga'), (3, 'Ophelia borealis'), (4, 'Eteone longa'), (5, 'Magelona johnstoni'), (6, 'Ochetostoma erythrogrammon'), (7, 'Pherecardia striata'), (8, 'Marphysa sanguinea'), (9, 'Phyllodoce rosea'); -- -------------------------------------------------------- -- -- Structure de la table `espece_zone` -- DROP TABLE IF EXISTS `espece_zone`; CREATE TABLE IF NOT EXISTS `espece_zone` ( `idZone` int(11) NOT NULL, `idEspece` int(11) NOT NULL, `quantite` int(11) NOT NULL, PRIMARY KEY (`idZone`,`idEspece`), KEY `idZone` (`idZone`), KEY `idEspece` (`idEspece`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `espece_zone` -- INSERT INTO `espece_zone` (`idZone`, `idEspece`, `quantite`) VALUES (1, 1, 65), (1, 7, 14), (1, 9, 25), (2, 3, 18), (2, 6, 47), (2, 7, 50), (3, 1, 31), (3, 2, 4), (3, 7, 39); -- -------------------------------------------------------- -- -- Structure de la table `etudes` -- DROP TABLE IF EXISTS `etudes`; CREATE TABLE IF NOT EXISTS `etudes` ( `idEtude` int(11) NOT NULL AUTO_INCREMENT, `nomEtude` varchar(50) NOT NULL, `ville` varchar(30) NOT NULL, `superficie` int(11) NOT NULL, `date` date NOT NULL, `validation` tinyint(1) NOT NULL, PRIMARY KEY (`idEtude`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; -- -- Contenu de la table `etudes` -- INSERT INTO `etudes` (`idEtude`, `nomEtude`, `ville`, `superficie`, `date`, `validation`) VALUES (1, 'Etude 001 - été 2016', 'biarritz', 5000, '2016-07-20', 1); -- -------------------------------------------------------- -- -- Structure de la table `zones` -- DROP TABLE IF EXISTS `zones`; CREATE TABLE IF NOT EXISTS `zones` ( `idZone` int(11) NOT NULL AUTO_INCREMENT, `nomZone` varchar(50) NOT NULL, `latA` float NOT NULL, `longA` float NOT NULL, `latB` float NOT NULL, `longB` float NOT NULL, `latC` float NOT NULL, `longC` float NOT NULL, `latD` float NOT NULL, `longD` float NOT NULL, `surface` int(11) NOT NULL, `validZone` tinyint(1) NOT NULL, `idEtude` int(11) NOT NULL, PRIMARY KEY (`idZone`), KEY `idEtude` (`idEtude`), KEY `idEtude_2` (`idEtude`), KEY `idEtude_3` (`idEtude`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- -- Contenu de la table `zones` -- INSERT INTO `zones` (`idZone`, `nomZone`, `latA`, `longA`, `latB`, `longB`, `latC`, `longC`, `latD`, `longD`, `surface`, `validZone`, `idEtude`) VALUES (1, 'Zone Alpha', 43.4845, -1.559, 43.4847, -1.55929, 43.4848, -1.55913, 43.4847, -1.55884, 536, 1, 1), (2, 'Zone Beta', 43.4835, -1.56061, 43.4836, -1.56038, 43.4839, -1.56074, 43.4838, -1.56094, 853, 1, 1), (3, 'Zone gamma', 43.4853, -1.55819, 43.4852, -1.55819, 43.4854, -1.55856, 43.4854, -1.55843, 238, 1, 1); -- -- Contraintes pour les tables exportées -- -- -- Contraintes pour la table `espece_zone` -- ALTER TABLE `espece_zone` ADD CONSTRAINT `espece_zone_ibfk_1` FOREIGN KEY (`idZone`) REFERENCES `zones` (`idZone`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `espece_zone_ibfk_2` FOREIGN KEY (`idEspece`) REFERENCES `especes` (`idEspece`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Contraintes pour la table `zones` -- ALTER TABLE `zones` ADD CONSTRAINT `zones_ibfk_1` FOREIGN KEY (`idEtude`) REFERENCES `etudes` (`idEtude`) ON DELETE CASCADE ON UPDATE CASCADE; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
160bf05f964166cca94eb843fa207482dabe1111
SQL
szzend/SQL
/触发器-更新用量(使用分子除以分母).sql
UTF-8
368
2.71875
3
[]
no_license
create trigger bombatchedit_for_fdosage on T_ENG_BOMCHILD after update as begin --update T_ENG_BOMCHILD set FDOSAGE =FNUMERATOR/FDENOMINATOR; update T_ENG_BOMCHILD set FDOSAGE =FNUMERATOR/FDENOMINATOR where FENTRYID in(select FENTRYID from inserted); --select * from inserted; --select * from T_ENG_BOMCHILD where FENTRYID in(select FENTRYID from inserted); end
true
b4f11925f8b466a02b6651a3f7fd319cfc85b1ca
SQL
johnjreiser/NJToolbox
/landuse/view_def.sql
UTF-8
536
3.4375
3
[]
no_license
-- Creates a table view that can be brought into Tableau for further exploration. DROP VIEW IF EXISTS landuse_export; CREATE OR REPLACE VIEW landuse_export AS SELECT a.yearcode, a.muncode, m.mun, m.county , a.lucode, l.ludesc, l.lutype , a.acres, a.isacres , (a.acres/(ST_Area(m.shape)/43560))::numeric(10,7) as pc_area , (a.isacres/(ST_Area(m.shape)/43560))::numeric(10,7) as pc_isarea FROM landuse_muni a LEFT JOIN lucrosswalk l ON a.lucode = l.lucode LEFT JOIN municipalities m ON a.muncode = m.mun_code ;
true
8ab2f7949892588bf50fcca965cfb29703cb160c
SQL
liuurick/spirngcloud2020
/db20.sql
UTF-8
843
2.828125
3
[]
no_license
/* Navicat Premium Data Transfer Source Server : 127.0.0.1 Source Server Type : MySQL Source Server Version : 50730 Source Host : localhost:3306 Source Schema : db20 Target Server Type : MySQL Target Server Version : 50730 File Encoding : 65001 Date: 14/08/2020 17:00:14 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for payment -- ---------------------------- DROP TABLE IF EXISTS `payment`; CREATE TABLE `payment` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '类别Id', `serial` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
true
8297c3e106d01ad52cb4f316d94e489f0050584b
SQL
funfunsin/SQL
/SQL Server 指令碼1/SQL Server 指令碼1/01select-1.sql
BIG5
646
3.25
3
[]
no_license
--Ƭd select 100 as 1,'' as 2 --from᭱@wƪ select Ǹ,mW,ʧO from ǥ --select ᭱ *N select * from ǥ --select iOW select Ǹ as Student_no,mW as Name,ʧO as Gender,q as Tel,ͤ as Birthday from ǥ --ƭB select mW,Ҧr,~,~-OI-| as bұo from u --rB select mW,+''+D as a},q from u --ƪB select Ǹ,mW,ͤ,GETDATE() as ,DATEDIFF(YEAR,ͤ,GETDATE()) as ~ from ǥ
true
0c3fe1cdf6e25a041312ea1c6b401452831e3a4c
SQL
splicemachine/benchmarks
/TPC-H/phoenix/explain/06.sql
UTF-8
241
3.015625
3
[ "Apache-2.0" ]
permissive
EXPLAIN SELECT SUM(L_EXTENDEDPRICE * L_DISCOUNT) AS REVENUE FROM TPCH.LINEITEM WHERE L_SHIPDATE >= TO_DATE('1994-01-01') AND L_SHIPDATE < TO_DATE('1995-01-01') AND L_DISCOUNT BETWEEN .06 - 0.01 AND .06 + 0.01 AND L_QUANTITY < 24 ;
true
b9922d29b77c8b9a7c44d9774d9c319a56f70fc6
SQL
1yena/SQL-STUDY
/07_DML.sql
UTF-8
3,131
4.09375
4
[]
no_license
-- DML ( Data Manipulation Language ) 작업 -- 데이터 입력( INSERT ) : 테이블에 새로운 행을 삽입. INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (300, 'Game', 100, 1700); -- 확인 ------------------------------------------------------------------------ SELECT * FROM departments ORDER by department_id DESC; -- 테이블 열의 구조를 확인 -------------------------------------------------------- DESC departments; -- 특정 열만 입력 시 미입력된 구간은 null 값이 됨. INSERT INTO departments(department_id, department_name) VALUES (280, 'Music'); -- 열의 이름들을 생략하더라도 값은 다 적어줘야지 삽입됨. INSERT INTO departments VALUES (290, 'Pusan', NULL, 1700); -- 안 적어도 NULL이고 'NULL'을 입력해도 NULL 값이 됨. -- 예제 1 INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (271, 'Sample Dept 1', 200, 1700); INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (272, 'Sample Dept 2', 200, 1700); INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (273, 'Sample Dept 3', 200, 1700); -- 기본키는 중복값 안 됨 = 똑같은 값을 중복으로 삽입하려하면 에러남. -- 데이터 수정( UPDATE ) [WHRER]절의 조건에 해당하는 행의 내용을 갱신함. UPDATE departments SET manager_id = 200 WHERE department_name = 'Game'; -- 예제 1 UPDATE departments SET manager_id = 100 WHERE department_id BETWEEN 150 and 200; -- 두 개 이상의 열을 업데이트하는 경우 SET에 (,) 찍고 조건 나열하면 됨. UPDATE departments SET manager_id = 100, location_id = 1800 WHERE department_name = 'Game'; -- 데이터 삭제( Delete ) : [WHRER]절의 조건에 해당하는 행단위로 데이터를 삭제한다. DELETE FROM departments WHERE department_id = 280; -- music 삭제 DELETE FROM departments WHERE department_id = 300; -- game 삭제 DELETE FROM departments WHERE department_id = 290; -- pusan 삭제 DELETE FROM departments WHERE department_name LIKE '%Sample%'; -- Sample 1,2,3 삭제 -- 전체삭제 : whrer 절을 안 적으면 전체삭제됨. DELETE FROM departments; -- 다른 테이블에서 해당 테이블을 참조하고 있기 때문에 바로 삭제가 안 됨. -- 120번 이상 부서들 삭제 DELETE FROM departments WHERE department_id >= 120; -- 커밋(commit) 전에는 롤백(rollback) 가능 ROLLBACK; -- 게임 부서를 생성하고 커밋(commit) INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (300, 'Game', 100, 1700); commit; -- 이제 롤백을 해도 게임 부서는 남아있음 -- 게임 부서 없애고 싶으면 삭제하고 커밋하면 됨. -- 자동 커밋 설정. SHOW autocommit; -- on.off 상태 확인. <"IMMEDIATE"는 "즉시"라는 뜻으로 자동커밋된 상태임> set autocommit on; -- 자동 커밋 on set autocommit off; -- 자동 커밋 off > 수동으로 커밋해줘야 함.
true
b9f0feec09f6bb668dfda86b588b0f1207361488
SQL
rafaelmakaha/bancos1
/04aula/extra01/aula4extra1_Fisico_RafaelMakaha_16-0142369.sql
UTF-8
1,255
3.515625
4
[]
no_license
/* Lógico: */ CREATE DATABASE aula4Extra1; USE aula4Extra1; CREATE TABLE DEPARTAMENTO ( codDepartamento INTEGER(8) NOT NULL, nome VARCHAR(50) NOT NULL, area VARCHAR(50) NOT NULL CONSTRAINT PK_DEPARTAMENTO PRIMARY KEY (codDepartamento) ); CREATE TABLE CURSO ( codCurso INTEGER(8) NOT NULL, nome VARCHAR(50) NOT NULL, creditoTotal INT(3) NOT NULL, codDepartamento INTEGER(8) NOT NULL CONSTRAINT PK_CURSO PRIMARY KEY (codCurso), CONSTRAINT FK_CURSO_DEPARTAMENTO FOREIGN KEY (codDepartamento) REFERENCES DEPARTAMENTO(codDepartamento) ); CREATE TABLE DISCIPLINA ( codDisciplina INTEGER(8) NOT NULL, nome VARCHAR(50) NOT NULL, credito INTEGER(3) NOT NULL, codCurso INTEGER(8) NOT NULL CONSTRAINT PK_DISCIPLINA PRIMARY KEY (codDisciplina), CONSTRAINT FK_DISCIPLINA_CURSO FOREIGN KEY (codCurso) REFERENCES CURSO (codCurso) ); CREATE TABLE requer ( codDisciplina INTEGER(8), codPreRequisito INTEGER(8), CONSTRAINT PK_requer PRIMARY KEY (codDisciplina, codPreRequisito), CONSTRAINT FK_requer_DISCIPLINA FOREIGN KEY (codDisciplina) REFERENCES DISCIPLINA (codDisciplina), CONSTRAINT FK_requer_DISCIPLINA FOREIGN KEY (CodPreRequisito) REFERENCES DISCIPLINA (codDisciplina) );
true
44f337fe714f86f8881466e8a84d063c3353c7fe
SQL
mhalvarez/Menu
/SCRIPTS ACTUALIZIONES/20110328.SQL
UTF-8
738
2.78125
3
[]
no_license
ALTER TABLE TH_PARA ADD (PARA_CTA4B VARCHAR2(15)); ALTER TABLE TH_PARA ADD (PARA_USA_CTA4B NUMBER DEFAULT 0); ALTER TABLE TH_PARA ADD (PARA_SECC_DEPNH VARCHAR2(15)); COMMENT ON COLUMN TH_PARA.PARA_CTA4B IS 'Cta. Pagos a Cuenta Departamento Depositos H.Lopez'; COMMENT ON COLUMN TH_PARA.PARA_USA_CTA4B IS 'Si se usa Campo PARA_CTA4B H.Lopez'; COMMENT ON COLUMN TH_PARA.PARA_SECC_DEPNH IS 'Codigo de Seccion Depositos en Newhotel H.Lopez'; ALTER TABLE TH_ASNT ADD (ASNT_DPTO_DESC VARCHAR2(256)); COMMENT ON COLUMN TH_ASNT.ASNT_DPTO_DESC IS 'Descripcion del Departamento NewHotel'; UPDATE TH_PARA SET PARA_FECHA_BASE = '28-MAR-2011'; UPDATE TH_PARA SET PARA_FECHA_EXE = '28-MAR-2011'; COMMIT;
true
1cb41cace1a9c018b1c31689fad3eec8a36f3d57
SQL
openfigis/figis
/figis-maintenance/src/main/resources/tony.sql
UTF-8
683
2.984375
3
[]
no_license
UPDATE fs_observation_xml x SET x.xml = ( select replace(x.xml, substr(x.xml, INSTR(x.xml, '<fi:ReportingYear>'), 41), '<fi:ReportingYear>' || ro.reporting_year || '</fi:ReportingYear>') from fs_resource_observation ro where ro.cd_observation = x.cd_observation and x.xml not like '%<fi:ReportingYear>' || ro.reporting_year ||'</fi:ReportingYear>%' and x.xml like '%<fi:ReportingYear>%' ) where x.cd_observation in ( select ro.cd_observation from fs_resource_observation ro, fs_observation_xml x where ro.cd_observation = x.cd_observation and x.xml not like '%<fi:ReportingYear>' || ro.reporting_year ||'</fi:ReportingYear>%' and x.xml like '%<fi:ReportingYear>%' ) ;
true
be5f0d51b2479750fe539a767d948beb7981c817
SQL
ABourcevet/SQLScript-fuer-SAP-HANA
/Listings/Kapitel 4/Listing 4.16.sql
ISO-8859-1
395
2.9375
3
[ "MIT" ]
permissive
-- Listing 4.16.sql -- Beispiel fr die TRIM-Funktionen SELECT TRIM(both 'HIA' FROM 'ABCDEFGHI') AS trim_both , TRIM(leading 'HIA' FROM 'ABCDEFGHI') AS trim_leading , TRIM(trailing 'HIA' FROM 'ABCDEFGHI') AS trim_trailing, LTRIM('ABCDEFGHI','HIA') AS "LTRIM()" , RTRIM('ABCDEFGHI','HIA') AS "RTRIM()" FROM dummy;
true
05452618c6f17bb6887f8ce98fb9726b50ec6f51
SQL
JoSuarezC/Agencia-de-Turismo
/Funcionalidad/ObtenciónBoleta.sql
ISO-8859-3
526
3.25
3
[]
no_license
CREATE PROCEDURE ObtecinBoleta @IdReservacion nvarchar(10) AS BEGIN if exists(SELECT * FROM Reservacion r WHERE r.IdReservacion = @IdReservacion) BEGIN SELECT rh.IdHotel, rh.Habitacion, rt.IdTransporte, rt.Aciento FROM Reservacion r inner join [Reservacion-Habitacion] rh on rh.IdReservacion = r.IdReservacion inner join [Reservacion-Transporte] rt on rt.IdReservacion = r.IdReservacion WHERE r.IdReservacion = @IdReservacion END else BEGIN Raiserror('La reservacin no existe',0,0) END END
true
ce786938a07e2319b660f03bde8a5b1c0fdebf73
SQL
tknemuru/SqlPuzzule
/レストランの空席.SQL
UTF-8
4,641
3.6875
4
[]
no_license
-- 回答 -- ビューの作成 CREATE VIEW EmptySeats(start_seat) AS SELECT MAIN_RST.seat + 1 FROM Restaurant MAIN_RST WHERE NOT EXISTS(SELECT 1 FROM Restaurant CHK_RST WHERE CHK_RST.seat = MAIN_RST.seat + 1) AND MAIN_RST.seat < 1000 UNION SELECT 1 FROM Restaurant MAIN_RST WHERE NOT EXISTS(SELECT 1 FROM Restaurant CHK_RST WHERE CHK_RST.seat = 1) -- セレクト文 SELECT START_EMP.start_seat , MIN(ISNULL(END_EMP.seat - 1, 1000)) AS end_date FROM EmptySeats AS START_EMP LEFT JOIN Restaurant AS END_EMP ON END_EMP.seat > START_EMP.start_seat GROUP BY START_EMP.start_seat --○1番:1年間はたらかなった後、5年間フルにノ働いた INSERT INTO Pensions VALUES('1', 2006, 12, 10); INSERT INTO Pensions VALUES('1', 2005, 12, 10); INSERT INTO Pensions VALUES('1', 2004, 12, 10); INSERT INTO Pensions VALUES('1', 2003, 12, 10); INSERT INTO Pensions VALUES('1', 2002, 12, 10); INSERT INTO Pensions VALUES('1', 2001, 0, 0); --○2番:10ヶ月 * 6年間 INSERT INTO Pensions VALUES('2', 2006, 10, 1); INSERT INTO Pensions VALUES('2', 2005, 10, 1); INSERT INTO Pensions VALUES('2', 2004, 10, 1); INSERT INTO Pensions VALUES('2', 2003, 10, 1); INSERT INTO Pensions VALUES('2', 2002, 10, 1); INSERT INTO Pensions VALUES('2', 2001, 10, 1); --×3番:10ヶ月 * 3年間, 1年休み, 10ヶ月 * 3 INSERT INTO Pensions VALUES('3', 2006, 10, 1); INSERT INTO Pensions VALUES('3', 2005, 10, 1); INSERT INTO Pensions VALUES('3', 2004, 10, 1); INSERT INTO Pensions VALUES('3', 2003, 0, 0); INSERT INTO Pensions VALUES('3', 2002, 10, 1); INSERT INTO Pensions VALUES('3', 2001, 10, 1); INSERT INTO Pensions VALUES('3', 2000, 10, 1); --×4番:10ヶ月 * 1年間, 1年休み, 10ヶ月 * 5 + 9ヶ月 INSERT INTO Pensions VALUES('4', 2007, 9, 1); INSERT INTO Pensions VALUES('4', 2006, 10, 1); INSERT INTO Pensions VALUES('4', 2005, 10, 1); INSERT INTO Pensions VALUES('4', 2004, 10, 1); INSERT INTO Pensions VALUES('4', 2003, 10, 1); INSERT INTO Pensions VALUES('4', 2002, 10, 1); INSERT INTO Pensions VALUES('4', 2001, 0, 0); INSERT INTO Pensions VALUES('4', 2000, 10, 1); --○5番:10ヶ月 * 1年間, 1年休み, 10ヶ月 * 6 INSERT INTO Pensions VALUES('5', 2007, 10, 1); INSERT INTO Pensions VALUES('5', 2006, 10, 1); INSERT INTO Pensions VALUES('5', 2005, 10, 1); INSERT INTO Pensions VALUES('5', 2004, 10, 1); INSERT INTO Pensions VALUES('5', 2003, 10, 1); INSERT INTO Pensions VALUES('5', 2002, 10, 1); INSERT INTO Pensions VALUES('5', 2001, 0, 0); INSERT INTO Pensions VALUES('5', 2000, 10, 1); --×6番:12ヶ月 * 4年間, 1年休み INSERT INTO Pensions VALUES('6', 2004, 0, 1); INSERT INTO Pensions VALUES('6', 2003, 12, 1); INSERT INTO Pensions VALUES('6', 2002, 12, 1); INSERT INTO Pensions VALUES('6', 2001, 12, 0); INSERT INTO Pensions VALUES('6', 2000, 12, 1); --○5番:10ヶ月 * 1年間, 1年休み, 10ヶ月 * 6 INSERT INTO Pensions VALUES('7', 2007, 10, 1); INSERT INTO Pensions VALUES('7', 2006, 10, 1); INSERT INTO Pensions VALUES('7', 2005, 10, 1); INSERT INTO Pensions VALUES('7', 2004, 10, 1); INSERT INTO Pensions VALUES('7', 2003, 10, 1); INSERT INTO Pensions VALUES('7', 2002, 10, 1); INSERT INTO Pensions VALUES('7', 2001, 10, 1); INSERT INTO Pensions VALUES('7', 2000, 10, 1); INSERT INTO Pensions VALUES('7', 1999, 0, 0); --○5番:10ヶ月 * 1年間, 1年休み, 10ヶ月 * 6 INSERT INTO Pensions VALUES('8', 2007, 10, 1); INSERT INTO Pensions VALUES('8', 2006, 10, 1); INSERT INTO Pensions VALUES('8', 2005, 10, 1); --○5番:10ヶ月 * 1年間, 1年休み, 10ヶ月 * 6 INSERT INTO Pensions VALUES('9', 2007, 10, 1); INSERT INTO Pensions VALUES('9', 2006, 10, 1); INSERT INTO Pensions VALUES('9', 2005, 10, 1); INSERT INTO Pensions VALUES('9', 2004, 10, 1); INSERT INTO Pensions VALUES('9', 2003, 10, 1); INSERT INTO Pensions VALUES('9', 2002, 10, 1); INSERT INTO Pensions VALUES('9', 2001, 10, 1); INSERT INTO Pensions VALUES('9', 2000, 10, 1); --○5番:10ヶ月 * 1年間, 1年休み, 10ヶ月 * 6 INSERT INTO Pensions VALUES('10', 2007, 10, 1); INSERT INTO Pensions VALUES('10', 2006, 10, 1); INSERT INTO Pensions VALUES('10', 2005, 10, 1); INSERT INTO Pensions VALUES('10', 2004, 10, 1); INSERT INTO Pensions VALUES('10', 2003, 10, 1); INSERT INTO Pensions VALUES('10', 2002, 9, 1); -- 59 INSERT INTO Pensions VALUES('10', 2001, 3, 1); -- 62 INSERT INTO Pensions VALUES('10', 2000, 2, 1); -- 64 INSERT INTO Pensions VALUES('10', 1999, 10, 1);
true
119ee5cb9106fcce4a007933d060b25cf2262110
SQL
TernopilJS/marketplace-api
/migrations/schema/0003_tables/chats/messages.sql
UTF-8
791
3.6875
4
[]
no_license
--liquibase formatted sql --changeset oleh:0003_messages splitStatements:false CREATE TABLE chat.messages ( id INT NOT NULL, chat_id UUID NOT NULL, owner_id UUID NOT NULL, text html_escaped_text NOT NULL, read BOOLEAN NOT NULL DEFAULT FALSE, created_at actual_timestamp, updated_at TIMESTAMPTZ, CONSTRAINT messages_pk PRIMARY KEY (id, chat_id), CONSTRAINT message_chat_fk FOREIGN KEY (chat_id) REFERENCES chat.chats (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, CONSTRAINT message_owner_fk FOREIGN KEY (owner_id) REFERENCES users (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED ); --rollback DROP TABLE chat.messages;
true
f860af4f46b7b8c1651c32010cfa0ee3062d3ec0
SQL
ibromley/info481-majorplan
/SQL/Creation.sql
UTF-8
1,214
3.625
4
[]
no_license
USE majorplan; CREATE TABLE MAJOR ( MajorID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (MajorID), MajorName varchar(200) ); CREATE TABLE TAG ( TagID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (TagID), TagName varchar(200) ); CREATE TABLE MAJOR_TAG ( MajorTagID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (MajorTagID), TagID INT, FOREIGN KEY (TagID) REFERENCES TAG(TagID), MajorID INT, FOREIGN KEY (MajorID) REFERENCES MAJOR(MajorID) ); CREATE TABLE REQ ( ReqID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (ReqID), ReqName varchar(500) ); CREATE TABLE MAJOR_REQ ( MajorReqID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (MajorReqID), ReqID INT, FOREIGN KEY (ReqID) REFERENCES REQ(ReqID), MajorID INT, FOREIGN KEY (MajorID) REFERENCES MAJOR(MajorID) ); CREATE TABLE COURSE ( CourseID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (CourseID), CourseName varchar(100), UNIQUE(CourseName) ); CREATE TABLE MAJOR_COURSE ( MajorCourseID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (MajorCourseID), CourseID INT, FOREIGN KEY (CourseID) REFERENCES COURSE(CourseID), MajorID INT, FOREIGN KEY (MajorID) REFERENCES MAJOR(MajorID), MinGrade FLOAT );
true
0a0d17d0002439948e2004d2c562ffe8b8c7255d
SQL
fanzs/lianjiashangcheng
/src/main/resources/database/lianjia.sql
GB18030
794
3.28125
3
[]
no_license
--address_support DROP TABLE IF EXISTS `support_address`; CREATE TABLE `support_address` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `belong_to` varchar(32) NOT NULL DEFAULT '0' COMMENT 'һλ', `en_name` varchar(32) NOT NULL COMMENT 'λӢд', `cn_name` varchar(32) NOT NULL COMMENT 'λ', `level` varchar(16) NOT NULL COMMENT ' -city -region', `baidu_map_lng` double NOT NULL COMMENT 'ٶȵͼ', `baidu_map_lat` double NOT NULL COMMENT 'ٶȵͼγ', PRIMARY KEY (`id`), UNIQUE KEY `unique_en_name_and_belong_to` (`en_name`,`level`,`belong_to`) USING BTREE COMMENT 'ÿеӢǶһ޶' ) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8mb4;
true
e4f56239e2623263b3e01ecebd4fb4cc1caebaa2
SQL
Product/ScratchProjects
/WebSpider/data.sql
UTF-8
273
2.84375
3
[]
no_license
create table webs.news ( id int auto_increment primary key, title varchar(255) null, content blob null, keywords varchar(127) null, summary varchar(511) null, time int null, url varchar(255) null, constraint news_url_uindex unique (url) ) collate=utf8mb4_bin;
true
a48d24d676a120604e3959750820dcb0b1ffb942
SQL
mubarakcoded/Online-Quiz-and-Test
/sql/setup.sql
UTF-8
4,835
3.8125
4
[]
no_license
CREATE DATABASE onlineclassroom; -- OWNER = mlewis as an option on personal machine. /* * The goal is to have Google login be the primary form of login be a Google login. I'm allowing a password field as the * backup. I'm going to store passwords properly for this application so they are slated and hashed. */ CREATE TABLE users ( id SERIAL PRIMARY KEY, email varchar(20) NOT NULL, password varchar(200) NOT NULL, instructor boolean NOT NULL ); CREATE TABLE course ( id SERIAL PRIMARY KEY, name varchar(20) NOT NULL, semester varchar(4) NOT NULL, section int NOT NULL, active boolean NOT NULL ); CREATE TABLE grade_formula ( id SERIAL PRIMARY KEY, courseid int NOT NULL REFERENCES course(id) ON DELETE CASCADE, grade_group varchar(20) NOT NULL, formula varchar(1000) NOT NULL ); CREATE TABLE user_course_assoc ( userid int NOT NULL REFERENCES users(id) ON DELETE CASCADE, courseid int NOT NULL REFERENCES course(id) ON DELETE CASCADE, time_multiplier double precision NOT NULL, PRIMARY KEY (userid, courseid) ); CREATE TABLE assessment ( id SERIAL PRIMARY KEY, name varchar(30) NOT NULL, description varchar(2000) NOT NULL, auto_grade int NOT NULL, creatorid int NOT NULL REFERENCES users(id) ON DELETE CASCADE ); /* * This associates an assessment with a course. The time values are all allowed to be null * because they are optional. Most things will have one or two of them specified, but none * are required. Students can't view the assessment until the start time and they can't * submit after the end time. Once they start, they have to be done in the allotted time * limit. */ CREATE TABLE assessment_course_assoc ( id SERIAL PRIMARY KEY, courseid int NOT NULL REFERENCES course(id) ON DELETE CASCADE, assessmentid int NOT NULL REFERENCES assessment(id) ON DELETE CASCADE, points int NOT NULL, grade_group varchar(20) NOT NULL, auto_grade int NOT NULL, start_time timestamp, end_time timestamp, time_limit int /* minutes that they have to work on this once they start. */ ); CREATE TABLE problem ( id SERIAL PRIMARY KEY, spec varchar(20000) NOT NULL, creatorid int NOT NULL REFERENCES users(id) ON DELETE CASCADE ); /* * This associates a problem to an assessment. */ CREATE TABLE problem_assessment_assoc ( id SERIAL PRIMARY KEY, assessmentid int NOT NULL REFERENCES assessment(id) ON DELETE CASCADE, problemid int NOT NULL REFERENCES problem(id) ON DELETE CASCADE, weight double precision NOT NULL, extra_credit boolean NOT NULL ); CREATE TABLE answer ( id SERIAL PRIMARY KEY, userid int NOT NULL REFERENCES users(id) ON DELETE CASCADE, courseid int NOT NULL REFERENCES course(id) ON DELETE CASCADE, paaid int NOT NULL REFERENCES problem_assessment_assoc(id) ON DELETE CASCADE, submit_time timestamp NOT NULL, details varchar(20000) NOT NULL ); CREATE TABLE answer_grade ( id SERIAL PRIMARY KEY, userid int NOT NULL REFERENCES users(id) ON DELETE CASCADE, courseid int NOT NULL REFERENCES course(id) ON DELETE CASCADE, paaid int NOT NULL REFERENCES problem_assessment_assoc(id) ON DELETE CASCADE, percent_correct double precision NOT NULL, comments varchar(200) NOT NULL ); CREATE TABLE assessment_start_time ( id SERIAL PRIMARY KEY, userid int NOT NULL REFERENCES users(id) ON DELETE CASCADE, acaid int NOT NULL REFERENCES assessment_course_assoc(id) ON DELETE CASCADE, time_started timestamp NOT NULL ); /********************************************************/ /* This code is an old version of answer_grade and what */ /* was written to correct it. */ /********************************************************/ CREATE TABLE answer_grade ( id SERIAL PRIMARY KEY, answerid int NOT NULL REFERENCES answer(id) ON DELETE CASCADE, percent_correct double precision NOT NULL, comments varchar(200) NOT NULL ); CREATE TABLE answer_grade_copy ( id SERIAL PRIMARY KEY, userid int NOT NULL REFERENCES users(id) ON DELETE CASCADE, courseid int NOT NULL REFERENCES course(id) ON DELETE CASCADE, paaid int NOT NULL REFERENCES problem_assessment_assoc(id) ON DELETE CASCADE, percent_correct double precision NOT NULL, comments varchar(200) NOT NULL ); INSERT INTO answer_grade_copy SELECT answer_grade.id, answer.userid, answer.courseid, answer.paaid, answer_grade.percent_correct, answer_grade.comments FROM answer, answer_grade WHERE answer.id=answer_grade.answerid; ALTER TABLE answer_grade RENAME TO answer_grade_old; ALTER TABLE answer_grade_copy RENAME TO answer_grade; DROP TABLE answer_grade_old; /** * Adding an active flag to the courses so I can prevent students from seeing questions in old courses. */ ALTER TABLE course ADD COLUMN active boolean; UPDATE course SET active = true; ALTER TABLE course ALTER COLUMN active SET NOT NULL;
true
38a7c6e13fe66376bb1338cee4dd593440520723
SQL
christiandeangelis/meetpad-public
/cdst-business/conferenza/src/main/resources/db/migration/V1.110__paleo_registry_filter.sql
UTF-8
474
2.90625
3
[]
no_license
CREATE SEQUENCE IF NOT EXISTS cdst.paleo_registry_filter_seq; CREATE TABLE IF NOT EXISTS cdst.paleo_registry_filter( id integer NOT NULL DEFAULT nextval('paleo_registry_filter_seq'::regclass), condizione character varying(255), fk_tipologia_conferenza integer, tipofiltro character varying(255) default 'TIPOCONFERENZA', codiceriferimento character varying(255), descrizione character varying(255), CONSTRAINT paleo_registry_filter_pkey PRIMARY KEY (id) );
true
f1c50b9fb5dcb71d9ef623bbf6cb8da8e0b1be9c
SQL
silence-do-good/stress-test-Postgres-and-MySQL
/dump/low/day22/select1438.sql
UTF-8
178
2.6875
3
[]
no_license
SELECT timeStamp, temperature FROM ThermometerOBSERVATION o WHERE timestamp>'2017-11-21T14:38:00Z' AND timestamp<'2017-11-22T14:38:00Z' AND temperature>=45 AND temperature<=92
true
ce323213c1146b60d47d06d7387482c9029e12b8
SQL
cider-load-test/ducks-on-rails
/db/migrate/sql/kooiRidSite.sql
UTF-8
1,067
3.3125
3
[]
no_license
-- Clean up: UPDATE `coordinate_decoys` SET h2 = NULL WHERE 1; -- Van de ringen zonder rid zijn er een aantal die qua locatie overlappen met een bestaande rid. -- Een deel daarvan ligt in de buurt van de buurt van een kooi. -- Wellicht zijn deze eenden in een kooi geringd, maar niet door de kooiker, -- of wellicht zijn ze wel door de kooiker geringd maar is de rid niet ingevoerd. -- Allereerst passen we het Hans 2 criterium toe, dus elimineren we alle locaties waar alleen -- pullen geringd zijn. UPDATE `coordinate_decoys` c JOIN ( SELECT lon, lat FROM `captures` c JOIN `capture_coordinates` cC ON c.sch = cC.sch AND c.ringnr = cC.ringnr AND c.occ = cC.occ JOIN `ringer_captures` rC ON c.sch = rC.sch AND c.ringnr = rC.ringnr AND c.occ = rC.occ WHERE age > 1 AND ringer_id IS NULL GROUP BY lon, lat ) h ON c.lon = h.lon AND c.lat = h.lat SET h2 = true; -- (Set the rest to false): UPDATE `coordinate_decoys` set h2 = false WHERE h2 IS NULL; -- Deze stap elimineert 49 locaties.
true
99a4bf72caa3f262438a6d363e05283d561d5c4a
SQL
OchaosO/JPASamples
/JpaSamplesWeb/sqlScripts/CreateTables.sql
UTF-8
1,023
2.890625
3
[ "MIT" ]
permissive
CREATE TABLE `authors` ( `id` int(11) NOT NULL, `name` varchar(100) DEFAULT NULL, `lastname` varchar(100) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, `telephone` varchar(100) DEFAULT NULL, `fax` varchar(100) DEFAULT NULL, `street` varchar(100) DEFAULT NULL, `zip` varchar(100) DEFAULT NULL, `city` varchar(100) DEFAULT NULL, `country` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `books` ( `id` int(11) NOT NULL, `name` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `publishers` ( `id` int(11) NOT NULL, `name` varchar(45) DEFAULT NULL, `email` varchar(45) DEFAULT NULL, `telephone` varchar(45) DEFAULT NULL, `fax` varchar(45) DEFAULT NULL, `street` varchar(45) DEFAULT NULL, `zip` varchar(45) DEFAULT NULL, `city` varchar(45) DEFAULT NULL, `country` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
true
2d78c643da953d3215de8147973e598f4a36d534
SQL
yaziedda/final-project-PBO
/database-import.sql
UTF-8
5,352
3.078125
3
[]
no_license
-- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 10.1.21-MariaDB - mariadb.org binary distribution -- Server OS: Win32 -- HeidiSQL Version: 9.3.0.4984 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8mb4 */; /*!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' */; -- Dumping database structure for fp_pbo CREATE DATABASE IF NOT EXISTS `fp_pbo` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `fp_pbo`; -- Dumping structure for table fp_pbo.app_user_data CREATE TABLE IF NOT EXISTS `app_user_data` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nama` varchar(50) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(200) NOT NULL, `role` int(11) NOT NULL COMMENT '0 admin, 1 user, 2 manager', `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `latest_login` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; -- Dumping data for table fp_pbo.app_user_data: ~2 rows (approximately) /*!40000 ALTER TABLE `app_user_data` DISABLE KEYS */; INSERT INTO `app_user_data` (`id`, `nama`, `username`, `password`, `role`, `created_at`, `latest_login`) VALUES (1, 'Yazied DAA', 'admin', 'admin', 0, '2017-11-20 23:37:49', '2017-12-11 22:04:05'), (10, 'Yazied', '1187', '123123', 2, '2017-12-09 01:39:01', '2017-12-09 01:39:20'); /*!40000 ALTER TABLE `app_user_data` ENABLE KEYS */; -- Dumping structure for table fp_pbo.app_user_regist CREATE TABLE IF NOT EXISTS `app_user_regist` ( `id` int(11) NOT NULL AUTO_INCREMENT, `ktp` varchar(50) DEFAULT NULL, `nik` varchar(50) DEFAULT NULL, `nama` varchar(50) DEFAULT NULL, `bagian` varchar(50) DEFAULT NULL, `created_at` datetime DEFAULT CURRENT_TIMESTAMP, `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `ktp` (`ktp`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- Dumping data for table fp_pbo.app_user_regist: ~2 rows (approximately) /*!40000 ALTER TABLE `app_user_regist` DISABLE KEYS */; INSERT INTO `app_user_regist` (`id`, `ktp`, `nik`, `nama`, `bagian`, `created_at`, `updated_at`) VALUES (1, 'qewq', 'qwe', 'qeq', 'qwe', '2017-12-11 23:17:02', '2017-12-11 23:17:02'), (2, '123', '111', 'qeq', 'qweqw', '2017-12-11 23:17:09', '2017-12-11 23:17:09'); /*!40000 ALTER TABLE `app_user_regist` ENABLE KEYS */; -- Dumping structure for table fp_pbo.master_barang CREATE TABLE IF NOT EXISTS `master_barang` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nama` varchar(100) DEFAULT NULL, `qty` double DEFAULT NULL, `created_at` datetime DEFAULT CURRENT_TIMESTAMP, `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1; -- Dumping data for table fp_pbo.master_barang: ~2 rows (approximately) /*!40000 ALTER TABLE `master_barang` DISABLE KEYS */; INSERT INTO `master_barang` (`id`, `nama`, `qty`, `created_at`, `updated_at`) VALUES (26, 'Laptop Lenovo 14 inch', 40, '2017-12-09 00:22:31', '2017-12-13 02:45:44'), (27, 'Proyektor Infocus', 50, '2017-12-09 00:23:11', '2017-12-09 00:23:11'); /*!40000 ALTER TABLE `master_barang` ENABLE KEYS */; -- Dumping structure for table fp_pbo.trx_pinjam CREATE TABLE IF NOT EXISTS `trx_pinjam` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_user` int(11) DEFAULT NULL, `id_barang` int(11) DEFAULT NULL, `qty` double DEFAULT NULL, `status` int(11) DEFAULT '0', `created_at` datetime DEFAULT CURRENT_TIMESTAMP, `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1; -- Dumping data for table fp_pbo.trx_pinjam: ~10 rows (approximately) /*!40000 ALTER TABLE `trx_pinjam` DISABLE KEYS */; INSERT INTO `trx_pinjam` (`id`, `id_user`, `id_barang`, `qty`, `status`, `created_at`, `updated_at`) VALUES (3, 2, 26, 1, 1, '2017-12-12 00:10:53', '2017-12-13 02:37:14'), (4, 2, 26, 1, 1, '2017-12-12 00:10:55', '2017-12-13 02:39:06'), (5, 2, 26, 1, 1, '2017-12-12 00:10:57', '2017-12-13 02:39:12'), (6, 2, 26, 1, 1, '2017-12-12 00:10:58', '2017-12-13 02:39:16'), (7, 2, 26, 5, 1, '2017-12-12 00:14:16', '2017-12-13 02:39:20'), (8, 2, 26, 4, 1, '2017-12-12 00:15:27', '2017-12-13 02:38:56'), (9, 2, 26, 3, 1, '2017-12-12 00:15:52', '2017-12-13 02:39:29'), (10, 2, 26, 3, 0, '2017-12-12 00:16:40', '2017-12-12 00:16:40'), (11, 2, 26, 4, 0, '2017-12-12 00:16:53', '2017-12-12 00:16:53'), (13, 2, 26, 9, 0, '2017-12-13 01:21:05', '2017-12-13 01:21:05'), (14, 2, 26, 3, 0, '2017-12-13 02:42:55', '2017-12-13 02:42:55'), (15, 2, 27, 40, 0, '2017-12-13 02:48:05', '2017-12-13 02:48:05'), (16, 2, 27, 1, 0, '2017-12-13 02:48:55', '2017-12-13 02:48:55'); /*!40000 ALTER TABLE `trx_pinjam` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
true
6f0c3b4711e529d1a0d4e121217d778020736223
SQL
donniezhanggit/Java-WebProject-JSP-MVC-JUnit-TestNG-Cucumber-Selenium
/Database/locations.sql
UTF-8
1,915
3.09375
3
[]
no_license
-------------------------------------------------------- -- File created - Friday-February-02-2018 -------------------------------------------------------- -------------------------------------------------------- -- DDL for Table LOCATIONS -------------------------------------------------------- CREATE TABLE "SYS"."LOCATIONS" ( "ID" NUMBER(3,0), "LOCATIONNAME" VARCHAR2(20 BYTE), "ADDRESS" VARCHAR2(20 BYTE), "ZIPCODE" NUMBER(5,0), "STAFFCOUNT" NUMBER(2,0), "CATERGORY" VARCHAR2(20 BYTE), "IMAGE" VARCHAR2(300 BYTE), "ACTIVE" NUMBER ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT) TABLESPACE "SYSTEM" ; REM INSERTING into SYS.LOCATIONS SET DEFINE OFF; Insert into SYS.LOCATIONS (ID,LOCATIONNAME,ADDRESS,ZIPCODE,STAFFCOUNT,CATERGORY,IMAGE,ACTIVE) values (1,'East Side','123 East Side',11222,10,'Full','" "',1); Insert into SYS.LOCATIONS (ID,LOCATIONNAME,ADDRESS,ZIPCODE,STAFFCOUNT,CATERGORY,IMAGE,ACTIVE) values (2,'West Side','123 West Side',11222,10,'Full','" "',1); -------------------------------------------------------- -- Constraints for Table LOCATIONS -------------------------------------------------------- ALTER TABLE "SYS"."LOCATIONS" MODIFY ("IMAGE" NOT NULL DISABLE); ALTER TABLE "SYS"."LOCATIONS" ADD PRIMARY KEY ("ID") DISABLE; ALTER TABLE "SYS"."LOCATIONS" MODIFY ("CATERGORY" NOT NULL DISABLE); ALTER TABLE "SYS"."LOCATIONS" MODIFY ("STAFFCOUNT" NOT NULL DISABLE); ALTER TABLE "SYS"."LOCATIONS" MODIFY ("ZIPCODE" NOT NULL DISABLE); ALTER TABLE "SYS"."LOCATIONS" MODIFY ("ADDRESS" NOT NULL DISABLE); ALTER TABLE "SYS"."LOCATIONS" MODIFY ("LOCATIONNAME" NOT NULL DISABLE); ALTER TABLE "SYS"."LOCATIONS" MODIFY ("ID" NOT NULL DISABLE);
true
2aad228ef2474216d18584d2943c12824bfb54b9
SQL
tkionshao/Cov_Push_Tool
/sp_history/SP_Sub_Generate_ACO_Report.sql
UTF-8
14,347
3.078125
3
[]
no_license
DELIMITER $$ USE `gt_gw_main`$$ DROP PROCEDURE IF EXISTS `SP_CreateDB_LTE`$$ CREATE DEFINER=`covmo`@`%` PROCEDURE `SP_Sub_Generate_ACO_Report`(IN GT_DB VARCHAR(100) ) BEGIN DECLARE O_GT_DB VARCHAR(100) DEFAULT GT_DB; DECLARE SH_EH VARCHAR(9) DEFAULT RIGHT(GT_DB,9); DECLARE START_TIME DATETIME DEFAULT SYSDATE(); DECLARE ACTIVE_CNT INT DEFAULT 0; DECLARE I INT DEFAULT 0 ; DECLARE WORKER_ID VARCHAR(10) DEFAULT CONNECTION_ID(); DECLARE CURRENT_NT_DB VARCHAR(50) DEFAULT CONCAT('gt_nt_',gt_strtok(GT_DB,3,'_')); INSERT INTO gt_gw_main.SP_LOG VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report','Start', START_TIME); INSERT INTO gt_gw_main.sp_log VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report','Step1', NOW()); SET @SqlCmd=CONCAT('DROP TABLE IF EXISTS ',GT_DB,'.tmp_opt_aco_traffic_unbalance;'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('CREATE TABLE ',GT_DB,'.`tmp_opt_aco_traffic_unbalance` ( `RNC_ID` mediumint(9) DEFAULT NULL, `CELL_ID` mediumint(9) DEFAULT NULL, `DATA_DATE` datetime DEFAULT NULL, `DATA_HOUR` tinyint(4) DEFAULT NULL, `PS_CALL_COUNT` mediumint(9) DEFAULT ''0'', `CS_CALL_COUNT` mediumint(9) DEFAULT ''0'', `AVG_RTWP` double DEFAULT NULL, `MAX_RTWP` double DEFAULT NULL, `MIN_THROUGHPUT` double DEFAULT NULL, `MAX_THROUGHPUT` double DEFAULT NULL, `AVG_THROUGHPUT` double DEFAULT NULL, `TRAFFIC_VOLUME_DIST` double DEFAULT NULL, `TOTAL_ERLANG_DIST` double DEFAULT NULL, `BLOCK_RATE` double DEFAULT NULL, `BLOCK_CALL_CNT` mediumint(9) DEFAULT ''0'', `BLOCK_WEIGHT` double DEFAULT NULL, `AVG_TRA_HIGH_THAN_NEB` double DEFAULT NULL, `NBR_CNT` mediumint(9) DEFAULT NULL, `CALL_CONCURRENT` mediumint(9) DEFAULT NULL, `FACTOR` double DEFAULT NULL, `AVG_TRA_DIFF_RATE` double DEFAULT NULL, `MAX_TRA_DIFF_RATE` double DEFAULT NULL, KEY `opt_aco_traffic_unbalance_idx1` (`CELL_ID`,`DATA_HOUR`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('Insert into ',GT_DB,'.tmp_opt_aco_traffic_unbalance SELECT RNC_ID,CELL_ID,DATA_DATE,DATA_HOUR ,SUM(PS_CALL_COUNT) AS PS_CALL_COUNT ,SUM(CS_CALL_COUNT) AS CS_CALL_COUNT ,NULL AS AVG_RTWP ,NULL AS MAX_RTWP ,MIN(MIN_THROUGHPUT) AS MIN_THROUGHPUT ,MAX(MAX_THROUGHPUT) AS MAX_THROUGHPUT ,SUM(AVG_THROUGHPUT_NUM)/SUM(AVG_THROUGHPUT_DEN) AS AVG_THROUGHPUT ,SUM(TRAFFIC_VOLUME_DIST) AS TRAFFIC_VOLUME_DIST ,SUM(TOTAL_ERLANG_DIST) AS TOTAL_ERLANG_DIST ,SUM(BLOCK_CALL_CNT)/SUM(BLOCK_DEN) AS BLOCK_RATE ,SUM(BLOCK_CALL_CNT) AS BLOCK_CALL_CNT ,POW(SUM(BLOCK_CALL_CNT),2)/SUM(BLOCK_DEN) AS BLOCK_WEIGHT ,NULL AS AVG_TRA_HIGH_THAN_NEB ,NULL AS NBR_CNT ,NULL AS CALL_CONCURRENT ,NULL AS FACTOR ,NULL AS AVG_TRA_DIFF_RATE ,NULL AS MAX_TRA_DIFF_RATE FROM ',GT_DB,'.opt_aco_traffic GROUP BY RNC_ID,CELL_ID,DATA_DATE,DATA_HOUR; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; INSERT INTO gt_gw_main.sp_log VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report','Step2', NOW()); SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_rtwp_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('CREATE TEMPORARY TABLE ',GT_DB,'.tmp_rtwp_',WORKER_ID,' as SELECT RNC_ID,CELL_ID,DATA_DATE,DATA_HOUR,AVG(COM_MEAS_VALUE) AS AVG_COM_MEAS_VALUE, MAX(COM_MEAS_VALUE) AS MAX_COM_MEAS_VALUE FROM ',GT_DB,'.table_nbap_cmr WHERE COM_MEAS_TYPE_ID=''1'' GROUP BY RNC_ID,CELL_ID ,DATA_DATE,DATA_HOUR; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SqlCmd=CONCAT('UPDATE ',GT_DB,'.tmp_opt_aco_traffic_unbalance A JOIN ',GT_DB,'.tmp_rtwp_',WORKER_ID,' B ON A.CELL_ID=B.CELL_ID AND A.RNC_ID=B.RNC_ID AND A.DATA_DATE=B.DATA_DATE AND A.DATA_HOUR=B.DATA_HOUR SET A.AVG_RTWP=B.AVG_COM_MEAS_VALUE ,A.MAX_RTWP=B.MAX_COM_MEAS_VALUE; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; INSERT INTO gt_gw_main.sp_log VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report','Step3', NOW()); SET @SqlCmd=CONCAT('DROP TABLE IF EXISTS ',GT_DB,'.tmp_aco_nt;'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('CREATE TABLE ',GT_DB,'.tmp_aco_nt as SELECT A.* FROM ',CURRENT_NT_DB,'.nt_current A INNER JOIN (SELECT DISTINCT RNC_ID,CELL_ID FROM ',GT_DB,'.tmp_opt_aco_traffic_unbalance) B ON A.RNC_ID=B.RNC_ID AND A.CELL_ID=B.CELL_ID; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SqlCmd=CONCAT('CREATE INDEX tmp_aco_nt_idx1 ON ',GT_DB,'.tmp_aco_nt(rnc_id,cell_id)'); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_aco_neighbor_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('CREATE TEMPORARY TABLE ',GT_DB,'.tmp_aco_neighbor_',WORKER_ID,' as SELECT DISTINCT A.RNC_ID,A.CELL_ID,B.NBR_RNC_ID,B.NBR_CELL_ID FROM ',GT_DB,'.tmp_aco_nt A INNER JOIN ',CURRENT_NT_DB,'.nt_neighbor_current B ON A.RNC_ID=B.RNC_ID AND A.CELL_ID=B.CELL_ID WHERE B.NBR_TYPE =1 UNION SELECT DISTINCT B.RNC_ID,B.CELL_ID,C.RNC_ID NBR_RNC_ID,C.CELL_ID NBR_CELL_ID FROM ',CURRENT_NT_DB,'.nt_neighbor_voronoi A INNER JOIN ',GT_DB,'.tmp_aco_nt B ON A.RNC_ID=B.RNC_ID AND A.SITE_ID=B.SITE_ID INNER JOIN ',GT_DB,'.tmp_aco_nt C ON A.NBR_RNC_ID=C.RNC_ID AND A.NBR_SITE_ID=C.SITE_ID WHERE B.DL_UARFCN=C.DL_UARFCN; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SqlCmd=CONCAT('UPDATE ',GT_DB,'.tmp_opt_aco_traffic_unbalance A , ( SELECT RNC_ID,CELL_ID ,COUNT(*) CNT FROM ',GT_DB,'.tmp_aco_neighbor_',WORKER_ID,' GROUP BY RNC_ID,CELL_ID ) B SET A.NBR_CNT=B.CNT WHERE A.RNC_ID=B.RNC_ID AND A.CELL_ID=B.CELL_ID; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; INSERT INTO gt_gw_main.sp_log VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report','Step4', NOW()); SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_aco_avg_tra_high_web_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SQLCMD=CONCAT ('CREATE TEMPORARY TABLE ',GT_DB,'.tmp_aco_avg_tra_high_web_',WORKER_ID,' as SELECT AA.RNC_ID,AA.CELL_ID,AA.DATA_HOUR ,TRAFFIC_VOLUME_DIST,(SUM(CASE WHEN TRAFFIC_VOLUME_DIST>TRAFFIC_VOLUME_DIST_NBR*1.2 THEN 1 ELSE 0 END)/NBR_CNT)AS AVG_TRA_HIGH_THAN_NEB FROM ',GT_DB,'.tmp_opt_aco_traffic_unbalance AA INNER JOIN ( SELECT A.DATA_HOUR,B.RNC_ID,B.CELL_ID,B.NBR_RNC_ID,B.NBR_CELL_ID,A.TRAFFIC_VOLUME_DIST AS TRAFFIC_VOLUME_DIST_NBR FROM ',GT_DB,'.tmp_opt_aco_traffic_unbalance A INNER JOIN ',GT_DB,'.tmp_aco_neighbor_',WORKER_ID,' B ON A.RNC_ID=B.NBR_RNC_ID AND A.CELL_ID=B.NBR_CELL_ID ) BB ON AA.RNC_ID=BB.RNC_ID AND AA.CELL_ID=BB.CELL_ID AND AA.DATA_HOUR=BB.DATA_HOUR GROUP BY RNC_ID,CELL_ID ,DATA_DATE,DATA_HOUR ; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SQLCMD=CONCAT ('UPDATE ',GT_DB,'.tmp_opt_aco_traffic_unbalance A,',GT_DB,'.tmp_aco_avg_tra_high_web_',WORKER_ID,' B SET A.AVG_TRA_HIGH_THAN_NEB=B.AVG_TRA_HIGH_THAN_NEB WHERE A.RNC_ID=B.RNC_ID AND A.CELL_ID=B.CELL_ID AND A.DATA_HOUR=B.DATA_HOUR; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SQLCMD=CONCAT ('UPDATE ',GT_DB,'.tmp_opt_aco_traffic_unbalance A, ( SELECT DATA_HOUR ,CELL_ID ,RNC_ID,MAX(MAX_CONCURRENT_CNT) MAX_CONCURRENT_CNT FROM ' ,O_GT_DB,'.opt_aco_traffic GROUP BY DATA_HOUR,CELL_ID,RNC_ID ) B SET A.CALL_CONCURRENT=B.MAX_CONCURRENT_CNT WHERE A.RNC_ID=B.RNC_ID AND A.CELL_ID=B.CELL_ID AND A.DATA_HOUR=B.DATA_HOUR; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SQLCMD=CONCAT ('UPDATE ',GT_DB,'.tmp_opt_aco_traffic_unbalance A SET FACTOR=POW(TRAFFIC_VOLUME_DIST,0.2) * SQRT(CALL_CONCURRENT) * BLOCK_RATE * AVG_TRA_HIGH_THAN_NEB; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; INSERT INTO gt_gw_main.sp_log VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report','Step5', NOW()); SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_aco_neighbor_traffic_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SQLCMD=CONCAT ('CREATE TEMPORARY TABLE ',GT_DB,'.tmp_aco_neighbor_traffic_',WORKER_ID,' as SELECT A.DATA_DATE,A.DATA_HOUR,B.RNC_ID,B.CELL_ID,MIN(A.TRAFFIC_VOLUME_DIST) NBR_TRAFFIC_VOLUME_DIST FROM ',GT_DB,'.tmp_opt_aco_traffic_unbalance A INNER JOIN ',GT_DB,'.tmp_aco_neighbor_',WORKER_ID,' B ON B.NBR_RNC_ID=A.RNC_ID AND B.NBR_CELL_ID=A.CELL_ID GROUP BY A.DATA_DATE,A.DATA_HOUR,B.RNC_ID,B.CELL_ID; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SQLCMD=CONCAT ('CREATE INDEX tmp_aco_neighbor_traffic_idx1 on ',GT_DB,'.tmp_aco_neighbor_traffic_',WORKER_ID,'(data_hour,cell_id) '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SQLCMD=CONCAT ('UPDATE ',GT_DB,'.tmp_opt_aco_traffic_unbalance A ,',GT_DB,'.tmp_aco_neighbor_traffic_',WORKER_ID,' b SET MAX_TRA_DIFF_RATE=(A.TRAFFIC_VOLUME_DIST-B.NBR_TRAFFIC_VOLUME_DIST)/A.TRAFFIC_VOLUME_DIST WHERE A.DATA_HOUR=B.DATA_HOUR AND A.CELL_ID=B.CELL_ID AND A.DATA_DATE=B.DATA_DATE AND A.RNC_ID=B.RNC_ID; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; INSERT INTO gt_gw_main.sp_log VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report','Step6', NOW()); SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_aco_neighbor_traffic_summary_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SQLCMD=CONCAT ('CREATE TEMPORARY TABLE ',GT_DB,'.tmp_aco_neighbor_traffic_summary_',WORKER_ID,' as SELECT A.DATA_DATE,A.DATA_HOUR,B.RNC_ID,B.CELL_ID,B.NBR_RNC_ID,B.NBR_CELL_ID ,A.TRAFFIC_VOLUME_DIST NBR_TRAFFIC_VOLUME_DIST FROM ',GT_DB,'.tmp_opt_aco_traffic_unbalance A INNER JOIN ',GT_DB,'.tmp_aco_neighbor_',WORKER_ID,' B ON B.NBR_RNC_ID=A.RNC_ID AND B.NBR_CELL_ID=A.CELL_ID; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SQLCMD=CONCAT ('CREATE INDEX tmp_aco_neighbor_traffic_summary_idx1 on ',GT_DB,'.tmp_aco_neighbor_traffic_summary_',WORKER_ID,'(data_hour,cell_id) '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; SET @SQLCMD=CONCAT ('UPDATE ',GT_DB,'.tmp_opt_aco_traffic_unbalance AA , ( SELECT B.RNC_ID,B.CELL_ID,B.DATA_DATE,B.DATA_HOUR ,SUM(A.TRAFFIC_VOLUME_DIST-B.NBR_TRAFFIC_VOLUME_DIST)/A.TRAFFIC_VOLUME_DIST/A.NBR_CNT AS AVG_TRA_DIFF_RATE FROM ',GT_DB,'.tmp_opt_aco_traffic_unbalance A INNER JOIN ',GT_DB,'.tmp_aco_neighbor_traffic_summary_',WORKER_ID,' b ON A.DATA_HOUR=B.DATA_HOUR AND A.CELL_ID=B.CELL_ID AND A.DATA_DATE=B.DATA_DATE AND A.RNC_ID=B.RNC_ID WHERE TRAFFIC_VOLUME_DIST>B.NBR_TRAFFIC_VOLUME_DIST GROUP BY DATA_DATE,DATA_HOUR,RNC_ID,CELL_ID ) CC SET AA.AVG_TRA_DIFF_RATE=CC.AVG_TRA_DIFF_RATE WHERE AA.DATA_HOUR=CC.DATA_HOUR AND AA.CELL_ID=CC.CELL_ID AND AA.DATA_DATE=CC.DATA_DATE AND AA.RNC_ID=CC.RNC_ID; '); PREPARE Stmt FROM @SqlCmd; EXECUTE Stmt; DEALLOCATE PREPARE Stmt; INSERT INTO gt_gw_main.sp_log VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report','Step7', NOW()); SET @SqlCmd=CONCAT('TRUNCATE TABLE ',GT_DB,'.opt_aco_traffic_unbalance;'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('INSERT INTO ',GT_DB,'.`opt_aco_traffic_unbalance` (`RNC_ID`, `CELL_ID`, `DATA_DATE`, `DATA_HOUR`, `PS_CALL_COUNT`, `CS_CALL_COUNT`, `AVG_RTWP`, `MAX_RTWP`, `MIN_THROUGHPUT`, `MAX_THROUGHPUT`, `AVG_THROUGHPUT`, `TRAFFIC_VOLUME_DIST`, `TOTAL_ERLANG_DIST`, `BLOCK_RATE`, `BLOCK_CALL_CNT`, `BLOCK_WEIGHT`, `AVG_TRA_HIGH_THAN_NEB`, `NBR_CNT`, `CALL_CONCURRENT`, `FACTOR`, `AVG_TRA_DIFF_RATE`, `MAX_TRA_DIFF_RATE`) SELECT `RNC_ID`, `CELL_ID`, `DATA_DATE`, `DATA_HOUR`, `PS_CALL_COUNT`, `CS_CALL_COUNT`, `AVG_RTWP`, `MAX_RTWP`, `MIN_THROUGHPUT`, `MAX_THROUGHPUT`, `AVG_THROUGHPUT`, `TRAFFIC_VOLUME_DIST`, `TOTAL_ERLANG_DIST`, `BLOCK_RATE`, `BLOCK_CALL_CNT`, `BLOCK_WEIGHT`, `AVG_TRA_HIGH_THAN_NEB`, `NBR_CNT`, `CALL_CONCURRENT`, `FACTOR`, `AVG_TRA_DIFF_RATE`, `MAX_TRA_DIFF_RATE` FROM ',GT_DB,'.tmp_opt_aco_traffic_unbalance;'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_rtwp_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('DROP TABLE IF EXISTS ',GT_DB,'.tmp_aco_nt;'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_aco_neighbor_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_aco_avg_tra_high_web_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_aco_neighbor_traffic_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @SqlCmd=CONCAT('DROP TEMPORARY TABLE IF EXISTS ',GT_DB,'.tmp_aco_neighbor_traffic_summary_',WORKER_ID,';'); PREPARE stmt FROM @sqlcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt; INSERT INTO gt_gw_main.SP_LOG VALUES(O_GT_DB,'Sp_Sub_Generate_ACO_Report',CONCAT('Done: ',TIMESTAMPDIFF(SECOND,START_TIME,SYSDATE()),' seconds.'), NOW()); END$$ DELIMITER ;
true
f6f0e3119a9da1c3c8ddba62927da1c25d6ff8e2
SQL
DrWereviruswolf/railway-ticket-database
/postgresql/createTable.sql
UTF-8
10,155
4.125
4
[ "LicenseRef-scancode-mulanpsl-2.0-en", "MulanPSL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CREATE TYPE TrainType as enum( 'C', 'D', 'G', 'K', 'T', 'Y', 'Z', '0' ); CREATE TYPE Access as enum( 'Passenger', 'Administrator' ); CREATE TYPE Status as enum( 'Reserved', 'Processing', 'Unfinished', 'Finished', 'Cancelled' ); CREATE TYPE SeatType as enum( 'hard_seat', 'soft_seat', 'hard_upper', 'hard_medium', 'hard_lower', 'soft_upper', 'soft_lower' ); --CREATE TABLE Train( -- tid CHAR(6) PRIMARY KEY, -- tname TrainType --); --WARNING --CREATE TABLE Seat( -- seat_type CHAR(8) PRIMARY KEY --); CREATE TABLE Station( s_sid INTEGER, s_sname VARCHAR(20) PRIMARY KEY, s_cityname VARCHAR(20) ); --Static data 7 CREATE TABLE TrainSchedule( ts_tid CHAR(6), ts_order INTEGER, ts_sname VARCHAR(20), ts_arrival_time TIME, ts_part_time TIME, ts_price DECIMAL(18, 2), ts_seat_type SeatType, FOREIGN KEY (ts_sname) REFERENCES Station(s_sname), PRIMARY KEY (ts_tid, ts_sname, ts_seat_type) ); --Dynamic data 6 [0:2] CREATE TABLE TrainByDate( tbd_tid CHAR(6), tbd_order INTEGER, tbd_sname VARCHAR(20), tbd_part_date DATE, tbd_seat_left INTEGER, tbd_seat_type SeatType, FOREIGN KEY (tbd_tid, tbd_sname, tbd_seat_type) REFERENCES TrainSchedule(ts_tid, ts_sname, ts_seat_type), PRIMARY KEY (tbd_tid, tbd_sname, tbd_seat_type, tbd_part_date) ); CREATE TABLE WebUser( u_uid VARCHAR(32) PRIMARY KEY, u_fullname VARCHAR(20), u_idcard CHAR(18), u_phone CHAR(11), u_credit CHAR(16), u_nickname VARCHAR(20), u_account DECIMAL(18, 2), u_access Access ); CREATE TABLE Reservation ( r_rid VARCHAR(32) PRIMARY KEY, r_uid VARCHAR(32), r_tid CHAR(6), r_tid2 CHAR(6), r_part_date DATE, r_part_sname VARCHAR(20), r_part_time TIME, r_arrival_sname VARCHAR(20), r_arrival_time TIME, r_part_date2 DATE, r_part_sname2 VARCHAR(20), r_part_time2 TIME, r_arrival_sname2 VARCHAR(20), r_arrival_time2 TIME, r_seat_type SeatType, r_seat_type2 SeatType, r_price DECIMAL(18, 2), r_status Status, FOREIGN KEY (r_uid) REFERENCES WebUser(u_uid) ); SELECT ts_sname, ts_arrival_time, ts_part_time, ts_price, ( SELECT MIN(tbd_seat_left) FROM TrainSchedule AS TS2, TrainByDate WHERE tbd_tid = TS1.ts_tid AND TS2.ts_seat_type = TS1.ts_seat_type AND tbd_part_date = DATE '2019-11-15' AND TS2.ts_order < TS1.ts_order ) AS temp_seat_left FROM TrainSchedule AS TS1, TrainByDate WHERE tbd_tid = ts_tid AND tbd_sname = ts_sname AND tbd_seat_type = ts_seat_type AND tbd_tid = 'G101' AND tbd_part_date = DATE '2019-11-15' AND tbd_seat_type = 'hard_seat' ORDER BY TS1.ts_order; SELECT P.ts_tid AS temp_tid, P.ts_seat_type AS temp_seat_type, P.ts_part_time AS temp_part_time, A.ts_arrival_time AS temp_arrival_time, P.ts_price AS temp_part_price, A.ts_price AS temp_arrival_price, P.ts_sname AS temp_part_sname, A.ts_sname AS temp_arrival_sname, ( SELECT MIN(tbd_seat_left) FROM TrainByDate WHERE tbd_tid = P.ts_tid AND tbd_seat_type = P.ts_seat_type AND tbd_order >= P.ts_order AND tbd_order < A.ts_order AND tbd_part_date = DATE '2019-11-14' ) AS temp_seat_left FROM ( SELECT * FROM TrainSchedule, Station WHERE ts_sname = s_sname AND s_cityname = '南京' AND ts_part_time >= '00:00:00' AND ts_price > 0 ) AS P, ( SELECT * FROM TrainSchedule, Station WHERE ts_sname = s_sname AND s_cityname = '北京' AND ts_price > 0 ) AS A WHERE P.ts_tid = A.ts_tid AND P.ts_seat_type = A.ts_seat_type AND P.ts_seat_type = 'hard_seat' AND P.ts_order < A.ts_order AND ( SELECT MIN(tbd_seat_left) FROM TrainByDate WHERE tbd_tid = P.ts_tid AND tbd_seat_type = P.ts_seat_type AND tbd_order >= P.ts_order AND tbd_order < A.ts_order AND tbd_part_date = DATE '2019-11-14' ) > 0 ORDER BY A.ts_price - P.ts_price, (A.ts_arrival_time - P.ts_part_time) + (INTERVAL '24 h' * (SELECT ( CASE WHEN A.ts_arrival_time < P.ts_part_time THEN 1 ELSE 0 END ))), P.ts_part_time LIMIT 10; UPDATE TrainByDate SET tbd_seat_left = 5 WHERE tbd_tid = 'G2' AND tbd_order = 2 AND tbd_seat_type = 'soft_seat' AND tbd_part_date = DATE '2019-11-14'; SELECT Train1.temp_tid AS temp_tid, Train2.temp_tid AS temp_tid2, Train1.temp_seat_type AS temp_seat_type, Train1.temp_part_time AS temp_part_time, Train1.temp_arrival_time AS temp_arrival_time, Train2.temp_part_time AS temp_part_time2, Train2.temp_arrival_time AS temp_arrival_time2, Train1.temp_part_price AS temp_part_price, Train1.temp_arrival_price AS temp_arrival_price, Train2.temp_part_price AS temp_part_price2, Train2.temp_arrival_price AS temp_arrival_price2, Train1.temp_part_sname AS temp_part_sname, Train1.temp_arrival_sname AS temp_arrival_sname, Train2.temp_part_sname AS temp_part_sname2, Train2.temp_arrival_sname AS temp_arrival_sname2, ( SELECT MIN(tbd_seat_left) FROM TrainByDate WHERE tbd_tid = Train1.temp_tid AND tbd_seat_type = Train1.temp_seat_type AND tbd_order >= Train1.temp_part_order AND tbd_order < Train1.temp_arrival_order AND tbd_part_date = DATE '2019-11-14' ) AS temp_seat_left, ( SELECT MIN(tbd_seat_left) FROM TrainByDate WHERE tbd_tid = Train2.temp_tid AND tbd_seat_type = Train2.temp_seat_type AND tbd_order >= Train2.temp_part_order AND tbd_order < Train2.temp_arrival_order AND ( Train1.temp_arrival_time > Train1.temp_part_time AND tbd_part_date = DATE '2019-11-14' OR Train1.temp_arrival_time < Train1.temp_part_time AND tbd_part_date = DATE '2019-11-14' + 1 ) ) AS temp_seat_left2 FROM ( SELECT P.ts_tid AS temp_tid, P.ts_seat_type AS temp_seat_type, P.ts_part_time AS temp_part_time, A.ts_arrival_time AS temp_arrival_time, P.ts_price AS temp_part_price, A.ts_price AS temp_arrival_price, P.ts_sname AS temp_part_sname, A.ts_sname AS temp_arrival_sname, S.s_cityname AS temp_arrival_cityname, P.ts_order AS temp_part_order, A.ts_order AS temp_arrival_order FROM ( SELECT * FROM TrainSchedule, Station WHERE ts_sname = s_sname AND s_cityname = '南京' AND ts_part_time >= TIME '00:00:00' AND ts_price > 0 ) AS P, ( SELECT * FROM TrainSchedule, Station WHERE ts_sname = s_sname AND ts_price > 0 ) AS A, Station AS S WHERE A.ts_sname = S.s_sname AND P.ts_tid = A.ts_tid AND P.ts_seat_type = A.ts_seat_type AND P.ts_seat_type = 'soft_seat' AND P.ts_order < A.ts_order ) AS Train1, ( SELECT P.ts_tid AS temp_tid, P.ts_seat_type AS temp_seat_type, P.ts_part_time AS temp_part_time, A.ts_arrival_time AS temp_arrival_time, P.ts_price AS temp_part_price, A.ts_price AS temp_arrival_price, P.ts_sname AS temp_part_sname, A.ts_sname AS temp_arrival_sname, P.ts_order AS temp_part_order, A.ts_order AS temp_arrival_order FROM ( SELECT * FROM TrainSchedule, Station WHERE ts_sname = s_sname AND ts_price > 0 ) AS P, ( SELECT * FROM TrainSchedule, Station WHERE ts_sname = s_sname AND s_cityname = '北京' AND ts_price > 0 ) AS A WHERE P.ts_tid = A.ts_tid AND P.ts_seat_type = A.ts_seat_type AND P.ts_seat_type = 'soft_seat' AND P.ts_order < A.ts_order ) AS Train2, Station AS S WHERE S.s_sname = Train2.temp_part_sname AND (( Train2.temp_part_time > Train1.temp_arrival_time AND Train2.temp_part_time - Train1.temp_arrival_time <= INTERVAL '4 h' AND (Train2.temp_part_sname = Train1.temp_arrival_sname AND Train2.temp_part_time - Train1.temp_arrival_time >= INTERVAL '1 h' OR (Train2.temp_part_sname <> Train1.temp_arrival_sname AND S.s_cityname = Train1.temp_arrival_cityname AND Train2.temp_part_time - Train1.temp_arrival_time >= INTERVAL '2 h')) ) OR ( Train2.temp_part_time < Train1.temp_arrival_time AND Train2.temp_part_time - Train1.temp_arrival_time + INTERVAL '24 h' <= INTERVAL '4 h' AND (Train2.temp_part_sname = Train1.temp_arrival_sname AND Train2.temp_part_time - Train1.temp_arrival_time + INTERVAL '24 h' >= INTERVAL '1 h' OR (Train2.temp_part_sname <> Train1.temp_arrival_sname AND S.s_cityname = Train1.temp_arrival_cityname AND Train2.temp_part_time - Train1.temp_arrival_time + INTERVAL '24 h' >= INTERVAL '2 h')) )) AND ( SELECT MIN(tbd_seat_left) FROM TrainByDate WHERE tbd_tid = Train1.temp_tid AND tbd_seat_type = Train1.temp_seat_type AND tbd_order >= Train1.temp_part_order AND tbd_order < Train1.temp_arrival_order AND tbd_part_date = DATE '2019-11-14' ) > 0 AND ( SELECT MIN(tbd_seat_left) FROM TrainByDate WHERE tbd_tid = Train2.temp_tid AND tbd_seat_type = Train2.temp_seat_type AND tbd_order >= Train2.temp_part_order AND tbd_order < Train2.temp_arrival_order AND ( Train1.temp_arrival_time > Train1.temp_part_time AND tbd_part_date = DATE '2019-11-14' OR Train1.temp_arrival_time < Train1.temp_part_time AND tbd_part_date = DATE '2019-11-14' + 1 ) ) > 0; INSERT INTO WebUser VALUES ('abcdefg', 'abc', '123456789987654321', '12345678909', '1234567887654321', 'abc', 0, 'Passenger'); SELECT ts_sname, ts_arrival_time, ts_part_time, ts_price, tbd_seat_left FROM TrainSchedule, TrainByDate WHERE tbd_tid = ts_tid AND tbd_sname = ts_sname AND tbd_seat_type = ts_seat_type AND tbd_tid = 'Z338' AND tbd_part_date = DATE '2019-11-14' AND tbd_seat_type = 'hard_upper'; SELECT ts_sname, ts_arrival_time, ts_part_time, ts_price, ( SELECT MIN(tbd_seat_left) FROM TrainSchedule AS TS2, TrainByDate WHERE TS2.ts_tid = TS1.ts_tid AND TS2.ts_seat_type = TS1.ts_seat_type AND tbd_part_date = DATE '2019-11-14' AND TS2.ts_order < TS1.ts_order ) AS temp_seat_left FROM TrainSchedule AS TS1, TrainByDate WHERE tbd_tid = ts_tid AND tbd_sname = ts_sname AND tbd_seat_type = ts_seat_type AND tbd_tid = 'G2' AND tbd_part_date = DATE '2019-11-14' AND tbd_seat_type = 'hard_seat' ORDER BY TS1.ts_order;
true
6f99417ee678514ac0f32e5e8dd30564293e666e
SQL
hellfyre/wishlist
/wishlist_tables.sql
UTF-8
2,953
3.46875
3
[ "MIT" ]
permissive
-- MySQL Script generated by MySQL Workbench -- So 25 Nov 2018 21:51:44 CET -- Model: wishlist 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 wishlist_db -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema wishlist_db -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `wishlist_db` DEFAULT CHARACTER SET utf8 ; USE `wishlist_db` ; -- ----------------------------------------------------- -- Table `wishlist_db`.`user` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `wishlist_db`.`user` ( `idUser` INT UNSIGNED NOT NULL AUTO_INCREMENT, `uName` VARCHAR(45) NOT NULL, `pwd` VARCHAR(255) NOT NULL, `first_name` VARCHAR(45) NULL DEFAULT NULL, `last_name` VARCHAR(45) NULL DEFAULT NULL, PRIMARY KEY (`idUser`), UNIQUE INDEX `idUsers_UNIQUE` (`idUser` ASC), UNIQUE INDEX `uName_UNIQUE` (`uName` ASC)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `wishlist_db`.`wishlist` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `wishlist_db`.`wishlist` ( `id_wishlist` INT UNSIGNED NOT NULL AUTO_INCREMENT, `id_user` INT UNSIGNED NOT NULL, `title` VARCHAR(256) NULL DEFAULT NULL, PRIMARY KEY (`id_wishlist`), UNIQUE INDEX `id_wishlist_UNIQUE` (`id_wishlist` ASC), INDEX `fk_wshlst_user_idx` (`id_user` ASC), CONSTRAINT `fk_wshlst_user` FOREIGN KEY (`id_user`) REFERENCES `wishlist_db`.`user` (`idUser`) ON DELETE CASCADE ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `wishlist_db`.`wish` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `wishlist_db`.`wish` ( `id_wish` INT UNSIGNED NOT NULL AUTO_INCREMENT, `id_wishlist` INT UNSIGNED NOT NULL, `title` VARCHAR(256) NOT NULL, `description` VARCHAR(512) NULL DEFAULT NULL, `url` VARCHAR(512) NULL DEFAULT NULL, `priority` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0, `price_low` DECIMAL(13,2) UNSIGNED NULL, `price_high` DECIMAL(13,2) UNSIGNED NULL, `amount` INT UNSIGNED NOT NULL DEFAULT 1, `reserved_key` VARCHAR(255) NULL DEFAULT NULL, `reserved` TINYINT(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id_wish`), INDEX `fk_wsh_wshlst_idx` (`id_wishlist` ASC), CONSTRAINT `fk_wsh_wshlst` FOREIGN KEY (`id_wishlist`) REFERENCES `wishlist_db`.`wishlist` (`id_wishlist`) ON DELETE CASCADE 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;
true
5fb060a35b07dfd8ff3f9a4e05c8b108c6a90c3c
SQL
inselberge/Coworks.In
/database/custom_sprocs/Event Counts by User.sql
UTF-8
119
3.609375
4
[]
no_license
select count(1) as count, u.fullName FROM Event e JOIN User u ON e.user_id=u.id GROUP BY user_id ORDER BY count DESC;
true
75f84148f6f2473f597f80818953edc018ab37b8
SQL
johncabang/v-opp
/backend/db/schema/02_posts.sql
UTF-8
656
3.109375
3
[]
no_license
DROP TABLE IF EXISTS posts CASCADE; CREATE TABLE posts( id SERIAL PRIMARY KEY NOT NULL, category VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, organization VARCHAR(255) NOT NULL, positions_available INTEGER, description TEXT, thumbnail_photo_url VARCHAR(255) NOT NULL, street VARCHAR(255) NOT NULL, city VARCHAR(255) NOT NULL, province VARCHAR(255) NOT NULL, post_code VARCHAR(255) NOT NULL, date_posted DATE NOT NULL, start_date DATE NOT NULL, requirements TEXT, additional_info TEXT, active BOOLEAN NOT NULL DEFAULT TRUE, user_id INTEGER REFERENCES users(id) ON DELETE CASCADE );
true
fa96b55852a45d8b1ae4614c6209d4708dc84ea1
SQL
vasantha1/5303-Database-Vasantha
/dbProject/documents/query_data.md.sql
UTF-8
8,074
3.3125
3
[]
no_license
### Title:Online Resume System Test Queries ### Names:Vasantha Gundeti,Sahaja Reddy Naredla #### Question 1: Show all Job seekers. SQL: ''' SELECT FIRST , last FROM user JOIN Roles ON Roles.User_ID = user.User_ID WHERE Role = 'jobseeker' LIMIT 0 , 30 ''' #### Answer: ''' first last serah van doorne oktay pauw necmettin coppes nataÅ¡a grob mischa voorhorst meine van eert mariella van aart kenan mikkers gerharda visch faouzi kee ashana obdam armaan balfoort abdÃkadir mast ''' #### Question 2: Show all employees. SQL: ''' SELECT FIRST , last FROM user JOIN Roles ON Roles.User_ID = user.User_ID WHERE Role = 'Employee' LIMIT 0 , 30 ''' #### Answer: ''' FIRST last sumaya helderman paolo davelaar milouda haase florijn van venrooij donato vreugdenhil ''' #### Question 3: Calculate the charge for job seeker X. SQL: ''' SELECT FIRST , last, SUM( Amount ) FROM user JOIN Charge_Users ON Charge_Users.User_ID = user.User_ID JOIN Applied_for ON Applied_for.User_ID = user.User_ID WHERE Applied_for.User_ID = 'M02' LIMIT 0 , 30 ''' #### Answer: ''' FIRST last Amount serah van doorne 20 ''' #### Question 4: Calculate the charge for company X SQL: ''' SELECT Company_Name, SUM( Amount ) FROM Company JOIN Charge_Company ON Charge_Company.Company_Id = Company.Company_Id JOIN Interviews ON Interviews.Company_Id = Company.Company_Id WHERE Interviews.Company_Id = '301' LIMIT 0 , 30 ''' #### Answer: ''' Company_Name SUM( Amount ) infosys 30 ''' #### Question 5: Find the company with the most jobs SQL: ''' SELECT Company_Id, COUNT( Company_Id ) n FROM Posted_Jobs GROUP BY Company_Id ORDER BY n DESC LIMIT 1 ''' #### Answer: ''' Company_Id n 301 3 ''' #### Question 6: Find the average # of interviews for all active users SQL: ''' SELECT ( COUNT( Company_ID ) / COUNT( DISTINCT ( User_ID ) ) ) AS avg FROM Interviews LIMIT 0 , 30 ''' ####Answer: ''' avg 1.4615 ''' #### Question 7: Add a new administrator(worker) SQL: ''' INSERT INTO USER( user_id, last, FIRST , street, city, state, zip, phone, email, PASSWORD , picture, SSN, Credit_Card_no, Expiration_Month, Expiration_Year, CVC ) VALUES ( 'M20', 'jackson', 'amy', '4700 taft', 'wichitafalls', 'texas', 76308, 9406134856, 'amyjackson@gmail.com', 12345, 'null', 4582163795, 347055608812334, 7, 2016, 714 ) ''' #### Question 8: Find the customer representative with most interviews SQL: ''' SELECT customer, COUNT( customer ) n FROM Interviews GROUP BY customer ORDER BY n DESC LIMIT 1 ''' #### Answer: ''' customer n develaar paolo 7 ''' #### Question 10: Find the company that generated the most interviews this month. SQL: ''' SELECT Company_Name, COUNT( Company_Name ) AS interviews FROM Company JOIN Interviews ON Interviews.Company_Id = Company.Company_Id GROUP BY Company_Name ORDER BY interviews DESC LIMIT 0 , ''' #### Answer: ''' Company_Name interviews Infosys 6 ''' #### Question:11 Find all interviews that were done last year. SQL: ''' SELECT * FROM Interviews WHERE YEAR( DATE ) =2014 LIMIT 0 , 30 ''' #### Answer: ''' Job_Category_ID Company_Id User_ID Date Completed 402 305 M11 2014-11-24 Yes 407 301 M09 2014-12-17 No 407 304 M06 2014-12-01 Yes ''' #### Question 12: Add a new job seeker SQL: ''' INSERT INTO USER( User_ID, last, FIRST , street, city, state, zip, phone, email, PASSWORD , picture, SSN, Credit_Card_no, Expiration_Month, Expiration_Year, CVC, Document, Date_Posted, Desired_Job_Categories ) VALUES ( 'M19', 'carter', 'julia', '1386 wycliff ave', 'bathurst', 'tasmania', '89584', '07-4814-7839', 'julia.carter@example.com', '7grout', '', '1333455676', '312040608872034', 12, 2019, 910, 'null', '2015-05-01', 'Dentist' ) ''' #### Question 14: Find the jobseeker with most scheduled interviews(meaning they are scheduled, but not completed) SQL: ''' SELECT FIRST , last, user.User_ID, COUNT( Interviews.User_ID ) c FROM Interviews JOIN user ON user.User_ID = Interviews.User_ID WHERE Completed = 'No' GROUP BY Interviews.User_ID ORDER BY c DESC LIMIT 1 ''' #### Answer: ''' FIRST last User_ID c oktay pauw M04 2 ''' #### Question 15: Find all jobs within category X. SQL: ''' SELECT Sub_Categories FROM Job_Categories WHERE Parent_Category = 'IT' LIMIT 0 , 30 ''' #### Answer: ''' Sub_Categories Database administrator Tester Developer ''' #### Question 16: Find all jobs within category X and subcategory 'Y' SQL: ''' SELECT DISTINCT Parent_Category, Sub_Categories, Job_Category_Name FROM Job_Categories WHERE Job_Category_Name IN ( 'Computers', 'Business' ) LIMIT 0 , 30 ''' #### Answer: ''' Parent_Category Sub_Categories Job_Category_Name IT Database administrator Computers Marketing Sales manager Business IT Tester Computers IT Developer Computers ''' #### Question 17: Find the count of currently posted jobs in each category and list from most to least. SQL: ''' SELECT Job_Category_Name, Parent_Category, Sub_Categories, COUNT( Sub_Categories ) AS n FROM Job_Categories JOIN Posted_Jobs ON Job_Categories.Job_Category_ID = Posted_Jobs.Job_Category_ID WHERE Date_Posted = current_date GROUP BY Sub_Categories ORDER BY n DESC LIMIT 0 , 30 ''' #### Answer: ''' Job_Category_Name Parent_Category Sub_Categories n Computers IT Developer 2 Finance Banking Cashier 1 Computers IT Database administrator ''' #### Question 18: Find the count of past posted jobs in each category and list from most to least. SQL: ''' SELECT Job_Category_Name, Parent_Category, Sub_Categories, COUNT( Sub_Categories ) AS n FROM Job_Categories JOIN Posted_Jobs ON Job_Categories.Job_Category_ID = Posted_Jobs.Job_Category_ID WHERE Date_Posted < current_date GROUP BY Sub_Categories ORDER BY n DESC LIMIT 0 , 30 ''' #### Answer: ''' Job_Category_Name Parent_Category Sub_Categories n Computers IT Tester 4 Computers IT Database administrator 1 Food Service Restaurant Manager 1 Health Science Medical Dentist 1 Business Marketing Sales manager 1 Computers IT Developer 1 ''' #### Question 19: Find the count of all posted jobs in each category and list by month. SQL: ''' SELECT Job_Category_Name, Parent_Category, Sub_Categories, Date_Posted, COUNT( Sub_Categories ) AS n FROM Job_Categories JOIN Posted_Jobs ON Job_Categories.Job_Category_ID = Posted_Jobs.Job_Category_ID GROUP BY Sub_Categories ORDER BY MONTH( Date_posted ) LIMIT 0 , 30 ''' #### Answer: ''' Job_Category_Name Parent_Category Sub_Categories Date_Posted n Health Science Medical Dentist 2015-05-20 1 Business Marketing Sales manager 2015-06-18 1 Food Service Restaurant Manager 2015-08-26 1 Computers IT Tester 2015-11-03 4 Finance Banking Cashier 2015-12-04 1 Computers IT Database administrator 2015-12-04 2 Computers IT Developer 2015-12-04 3 ''' #### Question 20: Add a job seeker SQL: ''' INSERT INTO USER( User_ID, last, FIRST , street, city, state, zip, phone, email, PASSWORD , picture, SSN, Credit_Card_no, Expiration_Month, Expiration_Year, CVC, Document, Date_Posted, Desired_Job_Categories ) VALUES ( 'M19', 'carter', 'julia', '1386 wycliff ave', 'bathurst', 'tasmania', '89584', '07-4814-7839', 'julia.carter@example.com', '7grout', '', '1333455676', '312040608872034', 12, 2019, 910, 'null', '2015-05-01', 'Dentist' ) ''' #### Question 21: Alter a posted job. SQL: ''' ALTER TABLE Posted_Jobs ADD Job_Description TEXT '''
true
62501149a131f7ff241e9d9986af32cc52f477e6
SQL
porscheYong/uoo
/doc/script/sql/AccessLog.sql
UTF-8
907
3.15625
3
[]
no_license
/* TRUNCATE TABLE LOG_ACCESS; DROP TABLE LOG_ACCESS; */ CREATE TABLE LOG_ACCESS( LOG_CA_ID NUMBER(12), CLAZZ VARCHAR(400), METHOD VARCHAR(100), IP VARCHAR(100), URLS VARCHAR(400), USER_ID NUMBER(12), OPERATE VARCHAR(10), COST_MILLIS NUMBER(12), ARGS CLOB, RESPONSE CLOB, CREATE_DATE DATE ) PARTITION BY RANGE(CREATE_DATE) ( PARTITION PART_01 VALUES LESS THAN (TO_DATE('2019-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss')) TABLESPACE USERS, PARTITION PART_02 VALUES LESS THAN (TO_DATE('2019-02-01 00:00:00','yyyy-mm-dd hh24:mi:ss')) TABLESPACE USERS, PARTITION PART_03 VALUES LESS THAN (TO_DATE('2019-03-01 00:00:00','yyyy-mm-dd hh24:mi:ss')) TABLESPACE USERS ); ALTER TABLE LOG_ACCESS ADD CONSTRAINT PK_LOG_ACCESS PRIMARY KEY(LOG_CA_ID); CREATE SEQUENCE SEQ_LOG_ACCESS_ID START WITH 1 INCREMENT BY 1 NOMAXVALUE NOMINVALUE NOCYCLE NOCACHE;
true
4b29f4d39ba46a8af23bb3022ac239ceb4cf2c0a
SQL
masihyeganeh/vulnerability-notifier
/database.sql
UTF-8
924
3.6875
4
[]
no_license
CREATE TABLE IF NOT EXISTS `sites` ( `id` int(10) unsigned NOT NULL, `address` varchar(250) NOT NULL, `email` varchar(250) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `site_technologies` ( `site_id` int(10) unsigned NOT NULL, `technology_id` int(10) unsigned NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `technologies` ( `id` int(10) unsigned NOT NULL, `name` varchar(50) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ALTER TABLE `sites` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `address` (`address`); ALTER TABLE `site_technologies` ADD KEY `site_id` (`site_id`), ADD KEY `technology_id` (`technology_id`); ALTER TABLE `technologies` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); ALTER TABLE `sites` MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT; ALTER TABLE `technologies` MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT;
true
879cfd143c679fa89e4c04dab55922a7bac68343
SQL
Francisco-Castillo/capitulo-jpa
/src/main/resources/universidad.sql
UTF-8
2,662
3.203125
3
[]
no_license
CREATE TABLE Facultades( idfacultad INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nombre VARCHAR(100) NOT NULL, abreviatura VARCHAR(20) ); CREATE TABLE Carreras( idcarrera INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nombre VARCHAR(150) NOT NULL, tipo INT NOT NULL, idfacultad INT NOT NULL ); ALTER TABLE Carreras ADD FOREIGN KEY (idfacultad) REFERENCES Facultades (idfacultad) ON UPDATE CASCADE; INSERT INTO Facultades(nombre,abreviatura) VALUES ("Facultad de Ciencias Exactas y Tecnologías","FCEyT"), ("Facultad de Humanidades, Ciencias Sociales y de la Salud","FHCSyS"), ("Facultad de Agronomía y Agroindustrias","FAyA"), ("Facultad de Ciencias Forestales","FCF"), ("Facultad de Ciencias Médicas","FCM"); INSERT INTO Carreras(nombre,idfacultad,tipo) VALUES ("Ingenieria Civil", 1, 2), ("Ingeniería Electromecánica", 1, 2), ("Ingeniería Electrónica", 1, 2), ("Ingeniería Eléctrica", 1, 2), ("Ingeniería en Agrimensura", 1, 2), ("Ingeniería Hidráulica", 1, 2), ("Ingeniería Industrial", 1, 2), ("Ingeniería Vial", 1, 2), ("Licenciatura en Hidrología Subterránea", 1, 2), ("Licenciatura en Matemática", 1, 2), ("Licenciatura en Matemática Nivel Terc", 1, 2), ("Licenciatura en Sistemas de Información", 1, 2), ("Profesorado en Informática", 1, 2), ("Profesorado en Matemática", 1, 2), ("Tecnicatura Universitaria en Construcción", 1, 3), ("Tecnicatura Universitaria Vial", 1, 3), ("Tecnicatura Universitaria en Hidrología Subterránea", 1, 3), ("Tecnicatura Universitaria en Organización y Control de la Producción", 1, 3), ("Programador Universitario en Informática", 1, 3), ("Licenciatura en Administración", 2, 2), ("Contador Público Nacional", 2, 2), ("Licenciatura en Letras", 2, 2), ("Licenciatura en Sociologia", 2, 2), ("Licenciatura en Enfermería", 2, 2), ("Lic. y Prof. Ed. para la salud", 2, 2), ("Licenciatura en Obstetricia", 2, 2), ("Licenciatura en Filosofía", 2, 2), ("Lic. en Trabajo Social", 2, 2), ("Lic. en Periodismo", 2, 2), ("Tec, Sup. Adm. y Gestión Universitaria", 2, 3), ("Tec. Edu. Intercultural Bilingue", 2, 3), ("Ingeniería Agronómica", 3, 2), ("Ingeniería en Alimentos", 3, 2), ("Licenciatura en Biotecnología", 3, 2), ("Licenciatura en Química", 3, 2), ("Profesorado en Química", 3, 2), ("Técnico Universitario en Apicultura", 3, 3), ("Ingeniería Forestal", 4, 2), ("Ingeniería en Industrias Forestales", 4, 2), ("Licenciatura en Ecología y Cons. del Med. Amb.", 4, 2), ("Tecnicatura Univ. Fitosanitarista", 4, 3), ("Tecnicatura Univ. en Viveros y Plant. Forestales", 4, 3), ("Tecnicatura Univ. en Aserraderos y Carpineria Ind", 4, 3), ("Medicina", 5, 2);
true
8498758076612bead076f30e84a57d43e83bbcdb
SQL
wanclee/datashaper
/samples/db2/dbscript/actproj-db2-identity-column-option.ddl
UTF-8
1,947
3.6875
4
[ "BSD-3-Clause" ]
permissive
# Copyright (C) 2010-2012, Wan Lee, wan5332@gmail.com DROP TABLE USR_LOC DROP TABLE USR DROP TABLE LOC DROP SEQUENCE ACTPROJ CREATE TABLE USR_LOC ( USR_LOC_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 30000, INCREMENT BY 1), LOC_ID BIGINT NOT NULL, USR_ID BIGINT NOT NULL, PRIMARY KEY (USR_LOC_ID) ) CREATE TABLE USR ( USR_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 30000, INCREMENT BY 1) , DESCRIPTION VARCHAR(256) , EMAIL VARCHAR(150) NOT NULL , BASE_PROFILE VARCHAR(400) , NAME VARCHAR(100) NOT NULL , USR_TYPE VARCHAR(30) NOT NULL , SYS_TENANT_ID BIGINT NOT NULL , PRIMARY KEY (USR_ID) ) CREATE TABLE LOC ( LOC_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 30000, INCREMENT BY 1) , NAME VARCHAR(200) NOT NULL , PRIMARY KEY (LOC_ID) ) ALTER TABLE USR_LOC ADD CONSTRAINT USR_LOC_LOC_FK1 FOREIGN KEY ( LOC_ID ) REFERENCES LOC ( LOC_ID ) ALTER TABLE USR_LOC ADD CONSTRAINT USR_LOC_USR_FK1 FOREIGN KEY ( USR_ID ) REFERENCES USR ( USR_ID ) #joined line version to please DB2 Command Line Processor: CREATE TABLE USR_LOC ( USR_LOC_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 30000, INCREMENT BY 1), LOC_ID BIGINT NOT NULL, USR_ID BIGINT NOT NULL, PRIMARY KEY (USR_LOC_ID) ) CREATE TABLE USR ( USR_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 30000, INCREMENT BY 1) , DESCRIPTION VARCHAR(256) , EMAIL VARCHAR(150) NOT NULL , BASE_PROFILE VARCHAR(400) , NAME VARCHAR(100) NOT NULL , USR_TYPE VARCHAR(30) NOT NULL , SYS_TENANT_ID BIGINT NOT NULL , PRIMARY KEY (USR_ID) ) CREATE TABLE LOC ( LOC_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 30000, INCREMENT BY 1) , NAME VARCHAR(200) NOT NULL , PRIMARY KEY (LOC_ID) ) ALTER TABLE USR_LOC ADD CONSTRAINT USR_LOC_LOC_FK1 FOREIGN KEY ( LOC_ID ) REFERENCES LOC ( LOC_ID ) ALTER TABLE USR_LOC ADD CONSTRAINT USR_LOC_USR_FK1 FOREIGN KEY ( USR_ID ) REFERENCES USR ( USR_ID )
true
9e85c26c8442a658e8da07eb2f7dcd1c5cfbe8d9
SQL
ChristopherChilders/restaurants-app
/examples.sql
UTF-8
1,718
3.1875
3
[]
no_license
-- user profile -- get all info for user by user_id -- get only a few fields for public version --get all fields for private version -- get all favorites for a user by favorites_id -- get all reviews written by that user by reviews_id -- restaurant profile -- get all info for a restaurant by id -- get all reviews for a restaurant by id -- get average review for a restaurant by id -- get count for favorites for restaurant by id -- restaurant search result (restaurants in Atlanta, GA) -- get all matching rows for restaurant by name (case insensitive search) -- include average review -- include # of favorites -- limit by minimum review -- (Super Bonus) pagination -- Restaurants -- 1 Fresh 111 Restaurant Dr. GA 1234567890 fresh.com/menu? fresh.pic -- 2 Ash's Burrito Shop 222 Tech Villiage Ln. GA 0987654321 ashburritohut.org/menu ash_makes_burritos.org/image -- 3 Ceil's Seasonal Seafood 333 Idonotknow St. CA 1112223333 runningouttaideas.com/menu guy-having-allergic-reaction.en -- 4 Pizzaborg 444 Thatsounds Cool Blvd. GA 4445556666 robotpizza.net/menu pizza-robot.com/dancingmakesyoudumb#thuglife#hanshotfirst#apimpnamedslickback -- Users -- 1 Chris Childers christopher.childers7@gmail.com GrumpyGrapes0 -- 2 Chris Aquino radishmouse@aol.com abc123 -- 3 Tenth Doctor tenthdoctor@who.tardis dalek -- 4 Ainz Ool Gown momanga@yggdrisil.net TheSorcerorKing -- 5 Scooby Doo mysterymachine@meddlingkids.dog ScoobySnack --Reviews -- 1 1 not only was the restaurant fake, but so was the address! 1 4 -- 2 5 Better than in my wildest dreams! 1 2 -- 3 3 The food was good. What wasn't so good was that I discovered a shellfish allergy :( 3 3 -- 4 5 Revery ring ras rerishish! 2 5 -- 5 1 I don't even know anymore 4 1 -- Favorites -- 1 5 1 -- 2 5 2 -- 3 5 3 -- 4 1 1 -- 5 5 4 -- 6 3 2
true
bffe4aad89ac0dd1fc76c0b306a29139d13a83f5
SQL
Escadev-SLDN2/JukeBox
/script_BDD/create_users.sql
UTF-8
450
2.765625
3
[]
no_license
USE jukebox; CREATE TABLE users ( id int auto_increment primary key, name varchar(50) not null, nickname varchar(25) not null, email varchar(50) not null, hash_pass varchar(255) not null, role varchar(25) ); INSERT INTO users( name,nickname,email,hash_pass,role ) VALUES( 'bob','marlon','bob@gmail.com','ABC$208f','ROLE_USER' ), ('booba','B2O','booba@hotgame.fr','BGRltlo6','ROLE_ADMIN' );
true
85be4f3dd6ae993a0479ec1f8a0ee6a11e7d023e
SQL
zdergatchev/Database-Basic
/13 Functions Triggers and Transactions Lab/02 Employees Promotion.sql
UTF-8
550
3.46875
3
[ "MIT" ]
permissive
DELIMITER $$ CREATE PROCEDURE usp_raise_salaries(department_name varchar(50)) BEGIN UPDATE `employees` SET `salary` = `salary` + 0.05 * `salary` WHERE `department_id` = (SELECT `department_id` FROM `departments` WHERE `name` = department_name); END$$ /* FOR judje */ /* CREATE PROCEDURE usp_raise_salaries(department_name varchar(50)) BEGIN UPDATE `employees` SET `salary` = `salary` + 0.05 * `salary` WHERE `department_id` = (SELECT `department_id` FROM `departments` WHERE `name` = department_name); END */
true