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
2d7224a8df3f4fb8c3a93f5441d98db0daf7464a
SQL
Magda7Lena/calendar
/src/main/resources/database/starter_db/06-lesson.sql
UTF-8
750
3.5
4
[]
no_license
--liquibase formatted sql --changeset magda:1 CREATE TABLE public.lesson (id bigint GENERATED ALWAYS AS IDENTITY NOT NULL, product_id bigint NOT NULL, instructor_id bigint NOT NULL, date date NOT NULL, time_start time without time zone NOT NULL, time_end time without time zone NOT NULL, description character varying(300) COLLATE pg_catalog."default", CONSTRAINT lesson_pkey PRIMARY KEY (id), CONSTRAINT instructor_id FOREIGN KEY (instructor_id) REFERENCES public.instructor (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT product_id FOREIGN KEY (product_id) REFERENCES public.product (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION)
true
04a339ba2fed1e9fb5a3feb7ddbd8d1049228d89
SQL
s18003/OracleKadai
/1212/1212.3.sql
UTF-8
147
2.765625
3
[]
no_license
select last_name, hire_date, salary from employees where hire_date between '06-01-01' and '06-12-31' and salary < 9000 and commission_pct is null;
true
f9362ccf7efb347076b2047a7d593afd2c2f05b1
SQL
aiemelyanov/RedGate
/TEST3/APEX_030200/Packages/WWV_RENDER_CALENDAR2.sql
UTF-8
3,736
3.265625
3
[]
no_license
CREATE OR REPLACE package apex_030200.wwv_render_calendar2 is -- Copyright (c) Oracle Corporation 1999. All Rights Reserved. -- -- DESCRIPTION -- Monthly calendar rendering -- -- SECURITY -- public execute -- -- RUNTIME DEPLOYMENT: YES -- -- NOTES -- Produces calendar HTML output from a SQL query that selects: -- Column1: Calendar date, must be an Oracle DATE datatype. -- Column2: Text to be displayed. -- Column3: Optional Link for Column2 text. -- Column4: Optional day link (link for day of month) use _calendar_dateYYYYMMDD_ or -- _calendar_date_ with p_calendar_day_date_fmt -- Column5: Frame Target -- Column6: Display color -- The query should have ordered by column 1. -- -- Parameters -- p_query query string or cursor -- select [date],[text],[text link],[day link],[frame target],[color] from ... -- example: select hiredate, ename, null, -- p_min_row the month to start, used for paginate -- p_max_rows maximum number of months to display -- p_min_month the month to start, used for paginate -- obsolete -- p_max_months maximum number of months to display -- obsolete -- p_monday_friday_only YES/NO, if YES, just display Monday to Friday -- p_month_font_face month font face -- p_month_font_size month font size -- p_month_font_color month font color -- p_day_font_face day font face -- p_day_font_size day font size -- p_day_font_color day font color -- p_cell_font_face cell font face -- p_cell_font_size cell font size -- p_cell_font_color cell font color -- p_page_width HTML table width -- p_heading_bg_color HTML table heading bg color -- p_table_bgcolor HTML table bg color -- -- g_status varchar2(200); g_total_rows number; g_total_months number; -- for paginate g_magic_date constant date := to_date('12111111','ddmmyyyy' ); -- magic date is Sunday -- procedure show ( p_query in varchar2 default null, p_min_month in number default 1, p_min_row in number default 1, p_max_months in number default 200, p_max_rows in number default 200, p_monday_friday_only in varchar2 default 'NO', p_month_font_face in varchar2 default null, p_month_font_size in varchar2 default null, p_month_font_color in varchar2 default null, p_day_font_face in varchar2 default null, p_day_font_size in varchar2 default null, p_day_font_color in varchar2 default null, p_cell_font_face in varchar2 default null, p_cell_font_size in varchar2 default null, p_cell_font_color in varchar2 default null, p_page_width in varchar2 default '90%', p_heading_bgcolor in varchar2 default '#C0C0A0', p_table_bgcolor in varchar2 default '#E0E0D0', -- p_table_cattributes in varchar2 default ' cellspacing="0" cellpadding="0"', p_show_month_above_tab in varchar2 default 'YES', p_non_curr_month_attr in varchar2 default 'bgcolor="#CCCCCC"', p_curr_day_attr in varchar2 default 'bgcolor="#FFFFCC"', p_min_blank_cell_height in varchar2 default '40', p_carot_character in varchar2 default '&#187;', p_calendar_day_date_fmt in varchar2 default 'MM/DD/YYYY', p_cur_local_date in date default null ); end wwv_render_calendar2; /
true
4ccf15fac1b739bd399338b21de73d57e405c73a
SQL
arik181/web.indow
/indow_reports/scripts/items_report.sql
UTF-8
831
3.25
3
[]
no_license
SELECT items.id, items.site_id, items.floor, items.room, items.location, items.width, items.height, edging.name, REPLACE(items.acrylic_panel_thickness, '"', ''), IF(items.special_geom = 0, 'false', 'true'), product_types.product_type, products.product, users.username, orders.updated FROM items INNER JOIN edging ON items.edging_id = edging.id INNER JOIN product_types ON items.product_types_id = product_types.id LEFT JOIN products ON items.window_shape_id = products.id INNER JOIN sites ON items.site_id = sites.id INNER JOIN users ON users.id = sites.created_by INNER JOIN orders ON items.order_id = orders.id INTO OUTFILE '/srv/jitterbit/items_report_tmp1.csv' FIELDS TERMINATED BY '|' ESCAPED BY '' ENCLOSED BY '"' LINES TERMINATED BY '\n' ;
true
66509446d6655eeec907702241c7073574fb947e
SQL
ashu2012/spark_2.1-scala_2.11-template
/src/main/resources/RAWBlackhillsExternalPhysicalStructures.sql
UTF-8
27,762
3.09375
3
[]
no_license
-- -- ER/Studio Data Architect SQL Code Generation -- Project : NTL Phase2 Model.DM1 -- -- Date Created : Wednesday, November 29, 2017 17:09:43 -- Target DBMS : Hive 0.12 -- -- -- TABLE: accounts -- CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`transformer_info`( site_name String, expected_technical_loss String, transformer_capacity String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Transformer/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`transformer_info_partitioned`( site_name String, expected_technical_loss String, transformer_capacity String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Transformer_partitioned/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`accounts`( account String, first_name String, last_name String, active String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Accounts/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`accounts_partitioned`( account String, first_name String, last_name String, active String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Accounts_partitioned/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`addresses`( site_name String, street String, city String, state String, zipcode String ) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde' WITH SERDEPROPERTIES("separatorChar" = ",","QUOTECHAR" = "`") STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Addresses/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`addresses_partitioned`( site_name String, street String, city String, state String, zipcode String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde' WITH SERDEPROPERTIES("separatorChar" = ",","QUOTECHAR" = "`") STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Addresses_partitioned/' ; -- -- TABLE: events -- CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`events`( meter_name String, event_datetime String, event_type String, event_name String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Events/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`events_partitioned`( meter_name String, event_datetime String, event_type String, event_name String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Events_partitioned/' ; -- -- TABLE: Stringerval -- CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`channels`( meter_name String, uom String, direction String, interval_length String, interval_count String, starting_interval_datetime String, value_1 String, quality_code_1 String, value_2 String, quality_code_2 String, value_3 String, quality_code_3 String, value_4 String, quality_code_4 String, value_5 String, quality_code_5 String, value_6 String, quality_code_6 String, value_7 String, quality_code_7 String, value_8 String, quality_code_8 String, value_9 String, quality_code_9 String, value_10 String, quality_code_10 String, value_11 String, quality_code_11 String, value_12 String, quality_code_12 String, value_13 String, quality_code_13 String, value_14 String, quality_code_14 String, value_15 String, quality_code_15 String, value_16 String, quality_code_16 String, value_17 String, quality_code_17 String, value_18 String, quality_code_18 String, value_19 String, quality_code_19 String, value_20 String, quality_code_20 String, value_21 String, quality_code_21 String, value_22 String, quality_code_22 String, value_23 String, quality_code_23 String, value_24 String, quality_code_24 String, value_25 String, quality_code_25 String, value_26 String, quality_code_26 String, value_27 String, quality_code_27 String, value_28 String, quality_code_28 String, value_29 String, quality_code_29 String, value_30 String, quality_code_30 String, value_31 String, quality_code_31 String, value_32 String, quality_code_32 String, value_33 String, quality_code_33 String, value_34 String, quality_code_34 String, value_35 String, quality_code_35 String, value_36 String, quality_code_36 String, value_37 String, quality_code_37 String, value_38 String, quality_code_38 String, value_39 String, quality_code_39 String, value_40 String, quality_code_40 String, value_41 String, quality_code_41 String, value_42 String, quality_code_42 String, value_43 String, quality_code_43 String, value_44 String, quality_code_44 String, value_45 String, quality_code_45 String, value_46 String, quality_code_46 String, value_47 String, quality_code_47 String, value_48 String, quality_code_48 String, value_49 String, quality_code_49 String, value_50 String, quality_code_50 String, value_51 String, quality_code_51 String, value_52 String, quality_code_52 String, value_53 String, quality_code_53 String, value_54 String, quality_code_54 String, value_55 String, quality_code_55 String, value_56 String, quality_code_56 String, value_57 String, quality_code_57 String, value_58 String, quality_code_58 String, value_59 String, quality_code_59 String, value_60 String, quality_code_60 String, value_61 String, quality_code_61 String, value_62 String, quality_code_62 String, value_63 String, quality_code_63 String, value_64 String, quality_code_64 String, value_65 String, quality_code_65 String, value_66 String, quality_code_66 String, value_67 String, quality_code_67 String, value_68 String, quality_code_68 String, value_69 String, quality_code_69 String, value_70 String, quality_code_70 String, value_71 String, quality_code_71 String, value_72 String, quality_code_72 String, value_73 String, quality_code_73 String, value_74 String, quality_code_74 String, value_75 String, quality_code_75 String, value_76 String, quality_code_76 String, value_77 String, quality_code_77 String, value_78 String, quality_code_78 String, value_79 String, quality_code_79 String, value_80 String, quality_code_80 String, value_81 String, quality_code_81 String, value_82 String, quality_code_82 String, value_83 String, quality_code_83 String, value_84 String, quality_code_84 String, value_85 String, quality_code_85 String, value_86 String, quality_code_86 String, value_87 String, quality_code_87 String, value_88 String, quality_code_88 String, value_89 String, quality_code_89 String, value_90 String, quality_code_90 String, value_91 String, quality_code_91 String, value_92 String, quality_code_92 String, value_93 String, quality_code_93 String, value_94 String, quality_code_94 String, value_95 String, quality_code_95 String, value_96 String, quality_code_96 String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Channels/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`channels_partitioned`( meter_name String, uom String, direction String, interval_length String, interval_count String, starting_interval_datetime String, value_1 String, quality_code_1 String, value_2 String, quality_code_2 String, value_3 String, quality_code_3 String, value_4 String, quality_code_4 String, value_5 String, quality_code_5 String, value_6 String, quality_code_6 String, value_7 String, quality_code_7 String, value_8 String, quality_code_8 String, value_9 String, quality_code_9 String, value_10 String, quality_code_10 String, value_11 String, quality_code_11 String, value_12 String, quality_code_12 String, value_13 String, quality_code_13 String, value_14 String, quality_code_14 String, value_15 String, quality_code_15 String, value_16 String, quality_code_16 String, value_17 String, quality_code_17 String, value_18 String, quality_code_18 String, value_19 String, quality_code_19 String, value_20 String, quality_code_20 String, value_21 String, quality_code_21 String, value_22 String, quality_code_22 String, value_23 String, quality_code_23 String, value_24 String, quality_code_24 String, value_25 String, quality_code_25 String, value_26 String, quality_code_26 String, value_27 String, quality_code_27 String, value_28 String, quality_code_28 String, value_29 String, quality_code_29 String, value_30 String, quality_code_30 String, value_31 String, quality_code_31 String, value_32 String, quality_code_32 String, value_33 String, quality_code_33 String, value_34 String, quality_code_34 String, value_35 String, quality_code_35 String, value_36 String, quality_code_36 String, value_37 String, quality_code_37 String, value_38 String, quality_code_38 String, value_39 String, quality_code_39 String, value_40 String, quality_code_40 String, value_41 String, quality_code_41 String, value_42 String, quality_code_42 String, value_43 String, quality_code_43 String, value_44 String, quality_code_44 String, value_45 String, quality_code_45 String, value_46 String, quality_code_46 String, value_47 String, quality_code_47 String, value_48 String, quality_code_48 String, value_49 String, quality_code_49 String, value_50 String, quality_code_50 String, value_51 String, quality_code_51 String, value_52 String, quality_code_52 String, value_53 String, quality_code_53 String, value_54 String, quality_code_54 String, value_55 String, quality_code_55 String, value_56 String, quality_code_56 String, value_57 String, quality_code_57 String, value_58 String, quality_code_58 String, value_59 String, quality_code_59 String, value_60 String, quality_code_60 String, value_61 String, quality_code_61 String, value_62 String, quality_code_62 String, value_63 String, quality_code_63 String, value_64 String, quality_code_64 String, value_65 String, quality_code_65 String, value_66 String, quality_code_66 String, value_67 String, quality_code_67 String, value_68 String, quality_code_68 String, value_69 String, quality_code_69 String, value_70 String, quality_code_70 String, value_71 String, quality_code_71 String, value_72 String, quality_code_72 String, value_73 String, quality_code_73 String, value_74 String, quality_code_74 String, value_75 String, quality_code_75 String, value_76 String, quality_code_76 String, value_77 String, quality_code_77 String, value_78 String, quality_code_78 String, value_79 String, quality_code_79 String, value_80 String, quality_code_80 String, value_81 String, quality_code_81 String, value_82 String, quality_code_82 String, value_83 String, quality_code_83 String, value_84 String, quality_code_84 String, value_85 String, quality_code_85 String, value_86 String, quality_code_86 String, value_87 String, quality_code_87 String, value_88 String, quality_code_88 String, value_89 String, quality_code_89 String, value_90 String, quality_code_90 String, value_91 String, quality_code_91 String, value_92 String, quality_code_92 String, value_93 String, quality_code_93 String, value_94 String, quality_code_94 String, value_95 String, quality_code_95 String, value_96 String, quality_code_96 String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Channels_partitioned/' ; -- -- TABLE: investigations -- CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`investigations`( site_name String, investigation_open_date String, arrival_date String, departure_date String, investigation_close_date String, investigation_reason String, outcome String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Investigations/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`investigations_partitioned`( site_name String, investigation_open_date String, arrival_date String, departure_date String, investigation_close_date String, investigation_reason String, outcome String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Investigations_partitioned/' ; -- -- TABLE: meters -- CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`meters`( meter_name String, site_name String, meter_type String, suspended String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Meters/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`meters_partitioned`( meter_name String, site_name String, meter_type String, suspended String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Meters_partitioned/' ; -- -- TABLE: registers -- CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`registers`( meter_name String, reading_datetime String, uom String, direction String, tou_tier String, measurement_period String, rollover_value String, value String, flags String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Registers/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`registers_partitioned`( meter_name String, reading_datetime String, uom String, direction String, tou_tier String, measurement_period String, rollover_value String, value String, flags String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Registers_partitioned/' ; -- -- TABLE: sites -- CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`sites`( site_name String, zipcode String, parent_site String, account String, latitude String, longitude String, site_zoning_category String, standard_use_description String, square_feet String, year_built String, assessor_market_value String, has_pool String, has_central_ac String, is_gas_user String, has_solar String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Sites/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`sites_partitioned`( site_name String, zipcode String, parent_site String, account String, latitude String, longitude String, site_zoning_category String, standard_use_description String, square_feet String, year_built String, assessor_market_value String, has_pool String, has_central_ac String, is_gas_user String, has_solar String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Sites_partitioned/' ; -- -- TABLE: woms -- CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`wom_events`( site_name String, event_datetime String, event_type String, event_name String ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Wom/' ; CREATE EXTERNAL TABLE IF NOT EXISTS dsp_ntl_memphis_raw.`wom_events_partitioned`( site_name String, event_datetime String, event_type String, event_name String ) PARTITIONED BY (`year` string,`month` string,`day` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION '#{StoragePath}/Wom_partitioned/' ;
true
d8eff9dd8fd1a5bc6956dd5bbb8cecc0314ae22c
SQL
Syndorik/Cher-voisin
/creationDB.sql
UTF-8
2,133
3.78125
4
[]
no_license
drop table if exists Users; drop table if exists Friends; drop table if exists Loans; drop table if exists Objects; drop table if exists Reviews; drop table if exists Godfathers; drop table if exists Groups; drop table if exists Titles; create table Users( user_ID serial unique, username VARCHAR(50) not null unique, last_name VARCHAR(50) not null, first_name VARCHAR(50) not null, email VARCHAR(50) not null unique, password VARCHAR(30) not null, group_ID int not null, address VARCHAR(50) null, tokens int not null, mark int not null check (mark <= 5), primary key (user_ID) ); create table Friends( user_ID1 int not null, user_ID2 int not null, primary key (user_ID1, user_ID2) ); create table Godfathers( godfather_ID int not null, godchild_ID int not null, primary key (godfather_ID, godchild_ID) ); create table Titles( user_ID int not null unique, borrower_title VARCHAR(50), lender_title VARCHAR(50), godfather_title VARCHAR(50), primary key (user_ID) ); create table Reviews( review_ID serial unique, loan_ID int not null, user_receiving int not null, user_giving int not null, mark int not null check (mark < 5), comment VARCHAR(200) not null, primary key (review_ID) ); create table Loans( loan_ID serial unique, object_ID int not null, borrower_ID int not null, loan_date date not null, loan_end_date date, primary key (loan_ID) ); create table Objects( object_ID serial unique, object_name VARCHAR(50) not null, owner_ID int not null, state boolean not null, category int, primary key (object_ID) ); create table Categories( category_id serial, category_name VARCHAR(50) not null, ); create table Groups( group_ID serial unique, group_name VARCHAR(90), primary key (group_ID) ); insert into Categories values 'Cooking'; insert into Categories values 'Gardening'; insert into Categories values 'Electronic'; insert into Categories values 'Sport'; insert into Categories values 'Diy'; insert into Categories values 'Diverse';
true
ffffb29d33146eede7d77dd82465023da9ec8387
SQL
vinaykarode/seo-audit
/models/base-adp/search-console/search_console_history.sql
UTF-8
517
3.90625
4
[]
no_license
SELECT b.run_date run_date, b.unix_run_date unix_run_date, account, a.client, platform, url, keyword, sum(impressions) as impressions_90d, sum(clicks) as clicks_90d, sum(clicks)/sum(impressions) as ctr_90d, sum(impressions * position)/sum(impressions) as pos_90d FROM {{ref('search_console_proc')}} a LEFT JOIN {{ ref('dates') }} b ON ( a.client = b.client ) WHERE a.unix_date >= ( b.unix_run_date - 90 ) AND a.unix_date <= b.unix_run_date group by run_date, unix_run_date, account, client, platform, url, keyword
true
8062b0bcea06c7e014111e84a9ded689a30d672d
SQL
muhammadhamdits/codersguild
/Tugasweb/dilla/database/tugascg.sql
UTF-8
3,946
2.84375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Waktu pembuatan: 01 Feb 2019 pada 02.28 -- Versi server: 10.1.32-MariaDB -- Versi PHP: 7.2.5 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `tugascg` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `tb_anggota` -- CREATE TABLE `tb_anggota` ( `id_anggota` varchar(50) NOT NULL, `nim` varchar(10) NOT NULL, `nama` varchar(100) NOT NULL, `email` varchar(50) NOT NULL, `jekel` varchar(10) NOT NULL, `tmp_lahir` varchar(50) NOT NULL, `tgl_lahir` date NOT NULL, `agama` varchar(15) NOT NULL, `goldar` varchar(2) NOT NULL, `sma` varchar(30) NOT NULL, `alamat` text NOT NULL, `no_hp` varchar(15) NOT NULL, `hobi` varchar(30) NOT NULL, `prestasi` text NOT NULL, `skill` text NOT NULL, `motto` varchar(250) NOT NULL, `foto` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tb_anggota` -- INSERT INTO `tb_anggota` (`id_anggota`, `nim`, `nama`, `email`, `jekel`, `tmp_lahir`, `tgl_lahir`, `agama`, `goldar`, `sma`, `alamat`, `no_hp`, `hobi`, `prestasi`, `skill`, `motto`, `foto`) VALUES ('160a16b7-ea61-42e7-a5ea-dbf7233e1094', '1711522014', 'Muhammad Hamdi', 'muhammad.hamdits@gmail.com', 'Laki-laki', 'Padang', '2000-02-03', 'Islam', 'A', 'MAN 2 Padang', 'Padang', '081234567890', 'Ngoding', 'Banyak', 'Banyak', 'Selamat dunia akhirat', '5c53994343210.jpg'), ('825f2ba6-5e01-4990-95fd-1b07b00ce0ad', '1711522012', 'Afif Maulana Isman', 'afif.mi@gmail.com', 'Laki-laki', 'Padang', '1998-11-30', 'Islam', 'O', 'SMAN 10 Kota Padang', 'Simp. Haru', '082386003596', 'Main Game', 'Satu-satunya yang dapat A- di matakuliah SDA yang diampu Bapak Matahari terbit dan bisa mengalahkan ketua club ini :v', 'Satu-satunya yang dapat A- di matakuliah SDA yang diampu Bapak Matahari terbit dan bisa mengalahkan ketua club ini :v', 'No Game No Live :v', '5c53979ac7714.jpeg'), ('a55eb578-df47-4aa7-889f-4fee7c40321c', '1711522020', 'Feny Mametri', 'feni.mametri@gmail.com', 'Perempuan', 'Agam', '2019-03-18', 'Islam', 'B', 'SMAN 1 Ampek Angkek', 'Pasa Baru', '083465432764', 'Main HP', 'Banyak', 'Banyak', 'Tanya ke orangnya', '5c5398d739b23.jpg'), ('a7169ba8-79f7-41de-b62f-7a09256b7318', '1711522012', 'Nadilla Cantik', 'nadila.syihaq8@gmail.com', 'Laki-laki', 'Muara Labuh', '2019-02-13', '', '', '', '', '082356752634', '', '', '', '', '5c539c5a713f4.png'), ('c9bd56ed-0eab-4df3-b04b-df6b10d13b54', '1711521015', 'Ovy Nanda Putri', 'ovy.np@gmail.com', 'Perempuan', 'Jambi', '1999-07-08', 'Islam', 'AB', 'SMAN 1 Sungai Penuh', 'Pasar Baru', '082345677654', 'Menipu Orang', 'Tanya ke orangnya', 'Menyebar rumor di lingkungan FTI', 'Tak bisa disebutkan dengan kata-kata', '5c5396a9d8b67.jpg'), ('d6982e97-7ee1-44af-bd29-eae14ddeb80c', '1711522002', 'Rahmania Jasmin', 'fara.rahmania@gmail.com', 'Perempuan', 'Jakarta', '2001-02-04', 'Islam', 'B', 'SMAN XX JAKARTA', 'Dekat kos dio', '082356752634', 'Belajar', 'Banyak', 'IP selalu tinggi', 'Tidak tau saya', '5c5399dd1c478.jpg'), ('e136925d-89a4-4df6-b9a8-b5313e72d90a', '1711521012', 'Nadilla Syihaq', 'nadila.syihaq8@gmail.com', 'Perempuan', 'Muara Labuh', '1999-01-08', 'Islam', 'O', 'SMAN 1 Kota Solok', 'Jln. Drs. Moh. Hatta - Kepalo Koto No. 5, Kota Padang', '082386003596', 'Banyak', 'Tidak ada yang bisa disebut sebagai prestasi', 'Sangat banyak sekali :v', 'Belum dipikirkan', '5c539916c6dd8.jpg'); -- -- Indexes for dumped tables -- -- -- Indeks untuk tabel `tb_anggota` -- ALTER TABLE `tb_anggota` ADD PRIMARY KEY (`id_anggota`); 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
27ddc6f7d5facaa18dc9747f88efb0ce33ce4568
SQL
xdcky/basdat_bimbel
/basdat_bimbel.sql
UTF-8
8,075
3.1875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 31 Jul 2018 pada 10.59 -- Versi Server: 10.1.13-MariaDB -- PHP Version: 7.0.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `basdat_bimbel` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `jadwal_kelas` -- CREATE TABLE `jadwal_kelas` ( `id` int(10) UNSIGNED NOT NULL, `id_kelas` int(10) UNSIGNED NOT NULL, `id_pengajar_pelajaran` int(10) UNSIGNED NOT NULL, `hari` enum('Senin','Selasa','Rabu','Kamis','Jumat','Sabtu','Minggu') NOT NULL, `jam_mulai` time NOT NULL, `jam_berakhir` time NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `jadwal_kelas` -- INSERT INTO `jadwal_kelas` (`id`, `id_kelas`, `id_pengajar_pelajaran`, `hari`, `jam_mulai`, `jam_berakhir`) VALUES (1, 1, 12, 'Kamis', '12:00:00', '15:00:00'), (2, 1, 12, 'Rabu', '23:00:00', '02:00:00'), (3, 2, 20, 'Rabu', '12:00:00', '13:00:00'); -- -------------------------------------------------------- -- -- Struktur dari tabel `kelas` -- CREATE TABLE `kelas` ( `id_kelas` int(10) UNSIGNED NOT NULL, `nama_kelas` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `kelas` -- INSERT INTO `kelas` (`id_kelas`, `nama_kelas`) VALUES (1, 'Djuanda - I'), (2, 'Djuanda - II'), (3, 'Djuanda - III'), (4, 'Soeharto - I'), (5, 'Kalkulus'); -- -------------------------------------------------------- -- -- Struktur dari tabel `mata_pelajaran` -- CREATE TABLE `mata_pelajaran` ( `kode_mapel` varchar(6) NOT NULL, `nama_pelajaran` varchar(30) NOT NULL, `tingkat_pendidikan` enum('SMA','SMP','SD') NOT NULL, `jurusan` enum('IPA','IPS','Bahasa') DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `mata_pelajaran` -- INSERT INTO `mata_pelajaran` (`kode_mapel`, `nama_pelajaran`, `tingkat_pendidikan`, `jurusan`) VALUES ('SMA101', 'Matematika', 'SMA', 'IPA'), ('SMA102', 'Bahasa Indonesia', 'SMA', 'IPA'), ('SMP101', 'Bahasa Indonesia', 'SMP', NULL), ('SMP102', 'Kimia', 'SMP', NULL); -- -------------------------------------------------------- -- -- Struktur dari tabel `nilai_siswa` -- CREATE TABLE `nilai_siswa` ( `id` int(10) UNSIGNED NOT NULL, `nis` char(10) NOT NULL, `id_pengajar_pelajaran` int(11) UNSIGNED NOT NULL, `nilai` int(3) UNSIGNED NOT NULL, `keterangan` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Struktur dari tabel `pengajar` -- CREATE TABLE `pengajar` ( `nip` char(18) NOT NULL, `nama_pengajar` varchar(50) NOT NULL, `jenis_kelamin` enum('Laki-laki','Perempuan') NOT NULL, `tanggal_lahir` date NOT NULL, `no_telepon` varchar(13) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `pengajar` -- INSERT INTO `pengajar` (`nip`, `nama_pengajar`, `jenis_kelamin`, `tanggal_lahir`, `no_telepon`) VALUES ('10116150', 'Dicky Hardiansyah', 'Laki-laki', '1997-12-12', '089712347654'), ('10116167', 'Satria Adi Putra', 'Laki-laki', '1998-09-14', '085770431325'); -- -------------------------------------------------------- -- -- Struktur dari tabel `pengajar_pelajaran` -- CREATE TABLE `pengajar_pelajaran` ( `id_pengajar_pelajaran` int(10) UNSIGNED NOT NULL, `nip` char(18) NOT NULL, `kode_mapel` varchar(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `pengajar_pelajaran` -- INSERT INTO `pengajar_pelajaran` (`id_pengajar_pelajaran`, `nip`, `kode_mapel`) VALUES (12, '10116167', 'SMA102'), (13, '10116167', 'SMP101'), (19, '10116150', 'SMA101'), (20, '10116150', 'SMP101'); -- -------------------------------------------------------- -- -- Struktur dari tabel `siswa` -- CREATE TABLE `siswa` ( `nis` char(10) NOT NULL, `nama_siswa` varchar(50) NOT NULL, `asal_sekolah` varchar(50) NOT NULL, `tanggal_lahir` date NOT NULL, `tingkat_pendidikan` enum('SMA','SMP','SD') NOT NULL, `jenis_kelamin` enum('Laki-laki','Perempuan') NOT NULL, `no_telepon` varchar(13) NOT NULL, `id_kelas` int(10) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `siswa` -- INSERT INTO `siswa` (`nis`, `nama_siswa`, `asal_sekolah`, `tanggal_lahir`, `tingkat_pendidikan`, `jenis_kelamin`, `no_telepon`, `id_kelas`) VALUES ('10116148', 'Dicky Hardiansyah', 'SMAN 1 Majalengka', '1997-12-12', 'SMP', 'Laki-laki', '089767652887', 2), ('10116150', 'Rahmad', 'SMA 1 Sumedang', '2018-07-02', 'SMA', 'Laki-laki', '097867656667', 2), ('10116156', 'Dzaki Fakhruddin', 'SMP 1 Cirebon', '1998-10-10', 'SMP', 'Laki-laki', '085770431325', 4), ('10116159', 'Ricky Fahmi Nugraha', 'SMAN 1 Majalengka', '1997-11-10', 'SMA', 'Laki-laki', '089712347654', 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `jadwal_kelas` -- ALTER TABLE `jadwal_kelas` ADD PRIMARY KEY (`id`), ADD KEY `fk_jadwal_kelas_id_kelas_idx` (`id_kelas`), ADD KEY `fk_jadwal_kelas_id_pengajar_pelajaran_idx` (`id_pengajar_pelajaran`); -- -- Indexes for table `kelas` -- ALTER TABLE `kelas` ADD PRIMARY KEY (`id_kelas`); -- -- Indexes for table `mata_pelajaran` -- ALTER TABLE `mata_pelajaran` ADD PRIMARY KEY (`kode_mapel`); -- -- Indexes for table `nilai_siswa` -- ALTER TABLE `nilai_siswa` ADD PRIMARY KEY (`id`), ADD KEY `fk_nilai_siswa_nisn_idx` (`nis`), ADD KEY `fk_nilai_siswa_id_pengajar_pelajaran_idx` (`id_pengajar_pelajaran`); -- -- Indexes for table `pengajar` -- ALTER TABLE `pengajar` ADD PRIMARY KEY (`nip`); -- -- Indexes for table `pengajar_pelajaran` -- ALTER TABLE `pengajar_pelajaran` ADD PRIMARY KEY (`id_pengajar_pelajaran`), ADD KEY `fk_pengajar_pelajaran_nip_idx` (`nip`), ADD KEY `fk_pengajar_pelajaran_kode_mp_idx` (`kode_mapel`); -- -- Indexes for table `siswa` -- ALTER TABLE `siswa` ADD PRIMARY KEY (`nis`), ADD KEY `fk_siswa_id_kelas_idx` (`id_kelas`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `jadwal_kelas` -- ALTER TABLE `jadwal_kelas` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `kelas` -- ALTER TABLE `kelas` MODIFY `id_kelas` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `pengajar_pelajaran` -- ALTER TABLE `pengajar_pelajaran` MODIFY `id_pengajar_pelajaran` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21; -- -- Ketidakleluasaan untuk tabel pelimpahan (Dumped Tables) -- -- -- Ketidakleluasaan untuk tabel `jadwal_kelas` -- ALTER TABLE `jadwal_kelas` ADD CONSTRAINT `fk_jadwal_kelas_id_kelas` FOREIGN KEY (`id_kelas`) REFERENCES `kelas` (`id_kelas`), ADD CONSTRAINT `fk_jadwal_kelas_id_pengajar_pelajaran` FOREIGN KEY (`id_pengajar_pelajaran`) REFERENCES `pengajar_pelajaran` (`id_pengajar_pelajaran`); -- -- Ketidakleluasaan untuk tabel `nilai_siswa` -- ALTER TABLE `nilai_siswa` ADD CONSTRAINT `fk_nilai_siswa_id_pengajar_pelajaran` FOREIGN KEY (`id_pengajar_pelajaran`) REFERENCES `pengajar_pelajaran` (`id_pengajar_pelajaran`), ADD CONSTRAINT `fk_nilai_siswa_nisn` FOREIGN KEY (`nis`) REFERENCES `siswa` (`nis`); -- -- Ketidakleluasaan untuk tabel `pengajar_pelajaran` -- ALTER TABLE `pengajar_pelajaran` ADD CONSTRAINT `fk_pengajar_pelajaran_kode_mp` FOREIGN KEY (`kode_mapel`) REFERENCES `mata_pelajaran` (`kode_mapel`), ADD CONSTRAINT `fk_pengajar_pelajaran_nip` FOREIGN KEY (`nip`) REFERENCES `pengajar` (`nip`); -- -- Ketidakleluasaan untuk tabel `siswa` -- ALTER TABLE `siswa` ADD CONSTRAINT `fk_siswa_id_kelas` FOREIGN KEY (`id_kelas`) REFERENCES `kelas` (`id_kelas`); /*!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
4db03e07489c2ab071c77b207f897899293ed878
SQL
rupalimayekar/SQL-Data-Analysis
/sakila/sakila_queries.sql
UTF-8
9,125
4.5
4
[]
no_license
-- Use the sakila database USE sakila; -- 1a. Display the first and last names of all actors from the table actor. SELECT first_name, last_name FROM actor; -- 1b. Display the first and last name of each actor in a single column in upper case letters. Name the column Actor Name. SELECT UPPER(CONCAT(first_name, " ", last_name)) AS 'Actor Name' from actor; -- 2a. You need to find the ID number, first name, and last name of an actor, of whom you know only the first name, "Joe." What is one query would you use to obtain this information? SELECT actor_id, first_name, last_name FROM actor WHERE UPPER(first_name) = 'JOE'; -- 2b. Find all actors whose last name contain the letters GEN: SELECT * FROM actor WHERE last_name LIKE '%GEN%'; -- 2c. Find all actors whose last names contain the letters LI. This time, order the rows by last name and first name, in that order: SELECT last_name, first_name FROM actor WHERE last_name like '%LI%' ORDER BY last_name, first_name; -- 2d. Using IN, display the country_id and country columns of the following countries: Afghanistan, Bangladesh, and China: SELECT country_id, country FROM country WHERE country IN ('Afghanistan', 'Bangladesh', 'China'); -- 3a. Add a middle_name column to the table actor. Position it between first_name and last_name. Hint: you will need to specify the data type. ALTER TABLE actor ADD COLUMN middle_name VARCHAR (45) AFTER first_name; -- 3b. You realize that some of these actors have tremendously long last names. Change the data type of the middle_name column to blobs. ALTER TABLE actor CHANGE middle_name middle_name BLOB; -- 3c. Now delete the middle_name column. ALTER TABLE actor DROP COLUMN middle_name; -- 4a. List the last names of actors, as well as how many actors have that last name. SELECT last_name, count(last_name) AS last_name_count FROM actor GROUP BY last_name; -- 4b. List last names of actors and the number of actors who have that last name, but only for names that are shared by at least two actors SELECT a.last_name, a.last_name_count FROM ( SELECT last_name, count(last_name) AS last_name_count FROM actor GROUP BY last_name ) a WHERE a.last_name_count = 2; -- 4c. Oh, no! The actor HARPO WILLIAMS was accidentally entered in the actor table as GROUCHO WILLIAMS, the name of Harpo's second cousin's husband's yoga teacher. Write a query to fix the record. SELECT * from actor WHERE last_name = 'WILLIAMS' AND first_name = 'GROUCHO'; UPDATE actor SET first_name = 'HARPO' WHERE last_name = 'WILLIAMS' AND first_name = 'GROUCHO'; -- 4d. Perhaps we were too hasty in changing GROUCHO to HARPO. It turns out that GROUCHO was the correct name after all! -- In a single query, if the first name of the actor is currently HARPO, change it to GROUCHO. Otherwise, -- change the first name to MUCHO GROUCHO, as that is exactly what the actor will be with the grievous error. -- BE CAREFUL NOT TO CHANGE THE FIRST NAME OF EVERY ACTOR TO MUCHO GROUCHO, HOWEVER! (Hint: update the record using a unique identifier.) UPDATE actor SET first_name = ( CASE first_name WHEN 'HARPO' THEN 'GROUCHO' ELSE 'MUCHO GROUCHO' END ) WHERE last_name = 'WILLIAMS' AND first_name = 'HARPO'; -- 5a. You cannot locate the schema of the address table. Which query would you use to re-create it? -- Hint: https://dev.mysql.com/doc/refman/5.7/en/show-create-table.html SHOW CREATE TABLE address; -- 6a. Use JOIN to display the first and last names, as well as the address, of each staff member. Use the tables staff and address: SELECT s.first_name, s.last_name, a.address FROM staff s INNER JOIN address a ON a.address_id = s.address_id SELECT * FROM payment; -- 6b. Use JOIN to display the total amount rung up by each staff member in August of 2005. Use tables staff and payment. SELECT s.staff_id, s.first_name, s.last_name, SUM(p.amount) AS total_cmount FROM payment p INNER JOIN staff s ON p.staff_id = s.staff_id WHERE p.payment_date LIKE '2005-08%' GROUP BY p.staff_id ; -- 6c. List each film and the number of actors who are listed for that film. Use tables film_actor and film. Use inner join. SELECT f.film_id, f.title, COUNT(fa.actor_id) AS count_of_actors FROM film f INNER JOIN film_actor fa ON f.film_id = fa.film_id GROUP BY fa.film_id ; -- 6d. How many copies of the film Hunchback Impossible exist in the inventory system? SELECT COUNT(*) FROM inventory WHERE film_id IN ( SELECT film_id from film WHERE title = 'Hunchback Impossible' ) ; -- 6e. Using the tables payment and customer and the JOIN command, list the total paid by each customer. List the customers alphabetically by last name: SELECT c.customer_id, c.last_name, c.first_name, SUM(p.amount) as total_amount_paid FROM customer c INNER JOIN payment p ON p.customer_id = c.customer_id GROUP BY p.customer_id ORDER BY c.last_name ; -- 7a. The music of Queen and Kris Kristofferson have seen an unlikely resurgence. As an unintended consequence, films starting with the letters K and Q have also soared in popularity. -- Use subqueries to display the titles of movies starting with the letters K and Q whose language is English. SELECT f.title FROM film f WHERE f.language_id = ( SELECT language_id FROM language l WHERE l.name = 'English' ) AND (f.title like 'K%' OR f.title LIKE 'Q%') ; -- 7b. Use subqueries to display all actors who appear in the film Alone Trip. SELECT a.first_name, a.last_name from actor a WHERE a.actor_id IN ( SELECT fa.actor_id FROM film_actor fa WHERE film_id IN ( SELECT film_id FROM film WHERE title = 'Alone Trip' ) ) ; -- 7c. You want to run an email marketing campaign in Canada, for which you will need the names and email addresses of all Canadian customers. -- Use joins to retrieve this information. SELECT c.first_name, c.last_name, c.email FROM customer c INNER JOIN address a ON c.address_id = a.address_id WHERE a.city_id IN ( SELECT ci.city_id from city ci INNER JOIN country co ON ci.country_id = co.country_id WHERE co.country = 'Canada' ) ; -- 7d. Sales have been lagging among young families, and you wish to target all family movies for a promotion. -- Identify all movies categorized as famiy films. SELECT f.title FROM film f WHERE f.film_id IN ( SELECT fc.film_id FROM film_category fc WHERE fc.category_id = ( SELECT c.category_id from category c WHERE c.name = 'Family' ) ) ; -- 7e. Display the most frequently rented movies in descending order. SELECT f.title, SUM(frequency) AS rental_frequency FROM (SELECT r.inventory_id, COUNT(r.inventory_id) AS frequency FROM rental r GROUP BY r.inventory_id ORDER BY frequency DESC) AS freq, inventory i, film f WHERE freq.inventory_id = i.inventory_id AND i.film_id = f.film_id GROUP BY f.film_id ORDER BY rental_frequency DESC ; -- 7f. Write a query to display how much business, in dollars, each store brought in. SELECT store.store_id, sum(sales) AS total_sales FROM (select staff_id, sum(amount) as sales from payment group by staff_id) as sales, staff, store WHERE sales.staff_id = staff.staff_id AND staff.store_id = store.store_id GROUP BY store.store_id -- 7g. Write a query to display for each store its store ID, city, and country. SELECT s.store_id, c.city, co.country FROM store s, address a, city c, country co WHERE s.address_id = a.address_id AND a.city_id = c.city_id AND c.country_id = co.country_id -- 7h. List the top five genres in gross revenue in descending order. (Hint: you may need to use the following tables: -- category, film_category, inventory, payment, and rental.) SELECT c.name AS genre, SUM(fr.revenue) AS gross_revenue FROM (SELECT i.film_id, SUM(sales.amount) AS revenue FROM (SELECT sum(amount) amount, inventory_id FROM payment p, rental r WHERE p.rental_id = r.rental_id GROUP BY r.inventory_id) AS sales, inventory i WHERE i.inventory_id = sales.inventory_id GROUP BY i.film_id ) AS fr, film_category fc, category c WHERE fr.film_id = fc.film_id AND fc.category_id = c.category_id GROUP BY c.category_id ORDER BY gross_revenue DESC ; -- 8a. In your new role as an executive, you would like to have an easy way of viewing the Top five genres by gross revenue. -- Use the solution from the problem above to create a view. If you haven't solved 7h, you can substitute another query to create a view. CREATE VIEW top_five_genres (id, genre, revenue) AS SELECT c.category_id, c.name AS genre, SUM(fr.revenue) AS gross_revenue FROM (SELECT i.film_id, SUM(sales.amount) AS revenue FROM (SELECT sum(amount) amount, inventory_id FROM payment p, rental r WHERE p.rental_id = r.rental_id GROUP BY r.inventory_id) AS sales, inventory i WHERE i.inventory_id = sales.inventory_id GROUP BY i.film_id ) AS fr, film_category fc, category c WHERE fr.film_id = fc.film_id AND fc.category_id = c.category_id GROUP BY c.category_id ORDER BY gross_revenue DESC LIMIT 5 ; -- 8b. How would you display the view that you created in 8a? SELECT * FROM top_five_genres; -- 8c. You find that you no longer need the view top_five_genres. Write a query to delete it. DROP VIEW top_five_genres;
true
18b17520f41bf4fbde7c3f7e99b15a54305450f5
SQL
gkhighelf/OpenRelayScaner
/Sql/database.sql
UTF-8
1,025
2.921875
3
[]
no_license
/** * Created by GKHighElf - gkhighelf@gmail.com * in near 2000 year, for self education and use. **/ create database statistics; DROP TABLE IF EXISTS `smtps`; CREATE TABLE `smtps` ( `subnet` int(4) unsigned NOT NULL default '0', `mask` int(4) unsigned NOT NULL default '0', `ip` int(4) unsigned NOT NULL default '0', `r1` char(255) NOT NULL default '', `r2` char(255) NOT NULL default '', `r3` char(255) NOT NULL default '', `r4` char(255) NOT NULL default '' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `world_subnets`; CREATE TABLE `world_subnets` ( `subnet` int(4) unsigned NOT NULL default '0', `mask` int(4) unsigned NOT NULL default '0', `country` char(2) NOT NULL default 'UA', `s_subnet` char(15) NOT NULL default '', `assigned` int(1) unsigned NOT NULL default '0', `iip` int(1) unsigned NOT NULL default '0', `pos` int(1) unsigned NOT NULL default '0', PRIMARY KEY (`subnet`), KEY `iip` (`iip`), KEY `assigned` (`assigned`,`iip`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
true
684a03113e672060efbe219fcca6a8ff067b5920
SQL
rheehot/codingtest-2
/Baekjoon/sm.sql
UTF-8
392
3.546875
4
[]
no_license
SELECT buyer_id,buy_date,book_name,price FROM library,orderInfo WHERE library.book_id = orderInfo.book_id and (book_name = "Looking with Elice" or buy_date between "2020-07-27" and "2020-07-31") ORDER BY buy_date asc; -- 두 개 테이블, 중복 안되게 만들고,합쳐진 테이블에서 특정 조건(조건 문자열과 같은거, 구매일자 특정범위 사이인거) 추출
true
3df2cfa10020e4d6f1ce4e8cc5d5e4bd2767cd31
SQL
andres18281/almacen
/almacen/db.sql
UTF-8
5,373
3.125
3
[]
no_license
Create Database dbAlmacen; Create Table Tipo_pantalon( Tip_codi_pant Int(2) Primary Key Not Null, Tiptipo_pantalon Varchar(10) Not Null); Create Table Tipo_persona( tip_perso Int(1) Primary Key Not Null, tipo_persona Varchar(10) Not Null); Insert Into Tipo_persona Values(1,"Hombre"); Insert Into Tipo_persona Values(2,"Mujer"); Insert Into Tipo_persona Values(3,"Niño"); Insert Into Tipo_persona Values(4,"Niña"); Create Table Pantalon( PantCodigo Varchar(10) Not Null Primary Key, PantColor Varchar(10) Not Null, PantTalla Varchar(2) Not Null, PantSexo Varchar(1)Not Null, PantTipo_pant Int(2) Not Null, PantItem Int(10) Not Null, PantTipo_persona Int(1) Not Null, Panvalor Int(10) Not Null, PantNit_provedor Int(10) Not Null); ALTER TABLE Pantalon Add Foreign Key(PantTipo_pant) References Tipo_pantalon(Tip_codi_pant); ALTER TABLE Pantalon Add Foreign Key(PantTipo_persona) References Tipo_persona(tip_perso); Create Table Tipo_camisa( TipCodi_camis Int(2) Not Null Primary Key, tipo_pant Varchar(10) Not Null); create Table Camisa( CamCodigo Varchar(10) Not Null Primary Key, CamColor Varchar(10) Not Null, CamTalla Varchar(2) Not Null, CamSexo Varchar(1) Not Null, CamTipo_camis Int(2) Not Null, CamItem Int(10) Not Null, Tipo_persona Int(1) Not Null, Camvalor Int(10) Not Null, CamNit_provedor Int(10) Not Null); ALTER TABLE Camisa ADD Foreign Key (CamTipo_camis) References Tipo_camisa(TipCodi_camis); ALTER TABLE Camisa ADD Foreign key(Tipo_persona)References Tipo_persona(Tip_perso); Create Table Tipo_Ropa_interior( RopaCod_pant Int(2) Not Null Primary Key, ropa_interior Varchar(10) Not Null); create Table Ropa_interior( RopCodigo Varchar(10) Not Null Primary Key, RopColor Varchar(10) Not Null, RopTalla Varchar(2) Not Null, RopSexo Varchar(1) Not Null, RopTipo_pant Int(2) Not Null, RopItem Int(10) Not Null, Tipo_persona Int(1) Not Null, Ropvalor Int(10) Not Null, RopNit_provedor Int(10) Not Null); ALTER TABLE Ropa_interior Add Foreign Key (RopTipo_pant) References Tipo_Ropa_interior(RopaCod_pant); ALTER TABLE Ropa_interior Add Foreign key (Tipo_persona) References Tipo_persona(Tip_perso); Create Table Tipo_calzado( TipCod_cal Int(1) Not Null Primary Key, Tipo_calzado Varchar(10)Not Null); create Table Calzado( CalCodigo Varchar(10) Primary Key Not Null, CalColor Varchar(10) Not Null, CalTalla Varchar(2) Not Null, CalSexo Varchar(1) Not Null, CalTipo_pant Int(2) Not Null, CalItem Int(10) Not Null, Tipo_persona Int(1) Not Null, Calvalor Int(10) Not Null, CalNit_provedor Int(10) Not Null); ALTER TABLE Calzado Add Foreign Key (CalTipo_pant) References Tipo_calzado(TipCod_cal); ALTER TABLE Calzado Add Foreign key (Tipo_persona) References Tipo_persona(Tip_perso); Create Table Juguetes( JugCodigo Varchar(10) Not Null Primary Key, Jugvalor Int(5) Not Null, JugTipo_niño Varchar(4) Not Null, Jug_marca Varchar(10) Not Null, JugNit_prov Int(10) Not Null); Create Table Factura( Fact_cod Int(10) ZEROFILL, FacCedula Int(10), FacNombre Varchar(10), Facfecha_venta Date, Fact_Total Int(10) Not Null); Primary Key Create table Item( Enum Int(1) Not Null Primary Key, Fact_cod Varchar(10) Not Null, tipo_producto Varchar(10) Not Null, nomb_prod Varchar(10) Not Null, Cantidad int(2) Not Null, costo int(6) Not Null, total int(7) Not Null); Insert into Tipo_pantalon Values(1,"Drill"); Insert into Tipo_pantalon Values(2,"Lino"); Insert into Tipo_pantalon Values(3,"BlueJeans"); Insert into Tipo_pantalon Values(4,"Pantaloneta"); Insert into Tipo_pantalon Values(5,"Capri"); Insert into Tipo_pantalon Values(6,"Shorts"); Insert into Tipo_pantalon Values(7,"Sudadera"); Insert into Tipo_pantalon Values(8,"Lewis"); Insert into Tipo_pantalon Values(9,"Licra"); Insert Into Tipo_camisa Values(1,"Camisa Manga Larga"); Insert Into Tipo_camisa Values(2,"Camisa Manga Corta"); Insert Into Tipo_camisa Values(3,"Buso Manga Larga"); Insert Into Tipo_camisa Values(4,"Buso Manga Corta"); Insert Into Tipo_camisa Values(5,"Camibuso tipo Polo"); Insert Into Tipo_camisa Values(6,"Camiseta Senc"); Insert Into Tipo_camisa Values(7,"Camis Senc Blan"); Insert Into Tipo_camisa Values(8,"Camisilla"); Insert Into Tipo_camisa Values(9,"Blusa Basica"); Insert Into Tipo_camisa Values(10,"Blusa"); Insert Into Tipo_camisa Values(11,"Bluson"); Insert Into Tipo_calzado Values(1,"Zapatilla"); Insert Into Tipo_calzado Values(2,"Zapato"); Insert Into Tipo_calzado Values(3,"Zapato Tela"); Insert Into Tipo_calzado Values(4,"Tipo Cross"); Insert Into Tipo_calzado Values(5,"Valeta"); Insert Into Tipo_calzado Values(6,"Zandalia"); Insert Into Tipo_calzado Values(7,"Chancla"); Insert Into Tipo_Ropa_interior Values(1,"Boxer"); Insert Into Tipo_Ropa_interior Values(2,"Calzonsillo"); Insert Into Tipo_Ropa_interior Values(3,"Interior"); Insert Into Tipo_Ropa_interior Values(4,"Brazilera"); Insert Into Tipo_Ropa_interior Values(5,"Calzonsillo"); Insert Into Tipo_Ropa_interior Values(6,"Calzon"); Insert Into Tipo_Ropa_interior Values(7,"Brasier"); Insert Into Tipo_Ropa_interior Values(8,"Top"); Insert Into Tipo_persona Values(1,"Hombre"); Insert Into Tipo_persona Values(2,"Mujer"); Insert Into Tipo_persona Values(3,"Niño"); Insert Into Tipo_persona Values(4,"Niña");
true
7f4c99e3b9d036308292abc5a01acb14b6e412af
SQL
ARigitano/Cocktails-Site
/database/cocktails_site.sql
UTF-8
7,620
2.859375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Hôte : 127.0.0.1 -- Généré le : mar. 08 juin 2021 à 15:31 -- Version du serveur : 10.4.19-MariaDB -- Version de PHP : 8.0.6 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 */; -- -- Base de données : `cocktails_site` -- -- -------------------------------------------------------- -- -- Structure de la table `cocktails` -- CREATE TABLE `cocktails` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `ingredients` varchar(1000) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Déchargement des données de la table `cocktails` -- INSERT INTO `cocktails` (`id`, `name`, `ingredients`) VALUES (1, 'Black Russian', 'Vodka;Kahlua'), (2, 'Margarita', 'Tequila;TripleSec;Lime'), (3, 'Absinth', 'Absinth;Water;SugarCube'), (4, 'Long Island Iced Tea', 'Vodka;Gin;RhumWhite;TripleSec;Tequila;Lemon;Cola'), (5, 'Perfect After Eight', 'Get27;LiquorWhiteCacao'), (6, 'Cuba Libre', 'RhumWhite;Lime;Cola'), (7, 'Expresso Martini', 'LiquorWhiteCacao;Kahlua;Vodka'), (8, 'Caipiroska', 'Vodka;Lime;SugarPowdered'), (9, 'Mojito', 'RhumWhite;Lime;Mint;WaterSparkling;SugarCaneSyrup'), (10, 'Aperol Spritz', 'WaterSparkling;WineWhite;Aperol'), (11, 'Pina Colada', 'RhumWhite;RhumDark;JuicePineapple;MilkCoconut'), (12, 'Daiquiri', 'RhumWhite;Lime;SugarCaneSyrup'), (13, 'Mai Tai', 'RhumWhite;RhumDark;TripleSec;SugarCaneSyrup;Lime;SyrupOrgeat'), (14, 'Grog', 'RhumWhite;SugarCube;Vanilla;Lemon;Cinnamon'), (15, 'Strawberry Mojito', 'RhumWhite;Mint;Lime;Strawberry;JuiceStrawberry;SugarCaneSyrup'), (16, 'Eggnog', 'Brandy;Milk;RhumDark;Egg;SugarPowdered;SourCreamLiquid'), (17, 'Royal Mojito', 'RhumWhite;Lime;SugarCaneSyrup;Mint;Champagne'), (18, 'Strawberry Daiquiri', 'LiquorStrawberry;RhumWhite;Lemon;SugarPowdered;Strawberry'), (19, 'Coco Loco', 'RhumWhite;CoconutMilk;SugarPowdered;Milk'), (20, 'Shrubb', 'SugarCaneSyrup;Orange;Mandarin;RhumWhite;Vanilla;Cinnamon;Nutmeg'), (21, 'Cosmopolitan', 'Vodka;TripleSec;JuiceCranberry;Lime'), (22, 'Caipirinha', 'Cachaca;Lime;SugarPowdered'), (23, 'Blue Lagoon', 'Vodka;CuracaoBlue;Lemon'), (24, 'Alaska', 'Gin;Chartreuse'), (26, 'Irish Coffee', 'Whiskey;Coffee;SugarCaneSyrup;SourCreamLiquid'), (27, 'Bazooka', 'Vodka;CuracaoBlue;Baileys'), (28, 'Bitter Sweet Symphony', 'Vodka;Campari;JuiceGrapefruit'); -- -------------------------------------------------------- -- -- Structure de la table `ingredients` -- CREATE TABLE `ingredients` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `type` enum('AlcoholStrong','AlcoholLow','Soft','Other') NOT NULL, `have` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Déchargement des données de la table `ingredients` -- INSERT INTO `ingredients` (`id`, `name`, `type`, `have`) VALUES (3, 'Vodka', 'AlcoholStrong', 1), (4, 'Kahlua', 'AlcoholLow', 1), (5, 'Tequila', 'AlcoholStrong', 1), (6, 'TripleSec', 'AlcoholLow', 1), (7, 'Lime', 'Other', 0), (8, 'Absinth', 'AlcoholStrong', 1), (9, 'Water', 'Soft', 1), (10, 'SugarCube', 'Other', 1), (11, 'Gin', 'AlcoholStrong', 1), (12, 'RhumWhite', 'AlcoholStrong', 1), (13, 'Lemon', 'Other', 1), (14, 'Cola', 'Soft', 0), (15, 'Get27', 'AlcoholLow', 1), (16, 'LiquorWhiteCacao', 'AlcoholLow', 1), (17, 'SugarPowdered', 'Other', 1), (18, 'Mint', 'Other', 0), (19, 'WaterSparkling', 'Soft', 1), (20, 'SugarCaneSyrup', 'Other', 1), (21, 'WineWhite', 'AlcoholLow', 0), (22, 'Aperol', 'AlcoholLow', 0), (23, 'RhumDark', 'AlcoholStrong', 0), (24, 'JuicePineapple', 'Soft', 0), (25, 'MilkCoconut', 'Soft', 0), (26, 'SyrupOrgeat', 'Other', 0), (27, 'Vanilla', 'Other', 0), (28, 'Cinnamon', 'Other', 1), (29, 'Strawberry', 'Other', 0), (30, 'JuiceStrawberry', 'Soft', 0), (31, 'Brandy', 'AlcoholStrong', 0), (32, 'Milk', 'Soft', 1), (33, 'Egg', 'Other', 1), (34, 'SourCreamLiquid', 'Other', 1), (35, 'Champagne', 'AlcoholLow', 0), (36, 'LiquorStrawberry', 'AlcoholLow', 1), (37, 'Orange', 'Other', 0), (38, 'Mandarin', 'Other', 0), (39, 'Nutmeg', 'Other', 0), (40, 'JuiceCranberry', 'Soft', 0), (41, 'Cachaca', 'AlcoholLow', 0), (42, 'CuracaoBlue', 'AlcoholLow', 1), (43, 'Whiskey', 'AlcoholStrong', 1), (44, 'Chartreuse', 'AlcoholStrong', 1), (45, 'Baileys', 'AlcoholLow', 1), (47, 'Campari', 'AlcoholLow', 1), (48, 'Picon', 'AlcoholLow', 1), (49, 'LiquorMandarin', 'AlcoholLow', 1), (50, 'Martini', 'AlcoholLow', 1), (51, 'LiquorLemon', '', 0), (52, 'GoldStrike', '', 0), (53, 'Suze', 'AlcoholLow', 1), (54, 'Porto', 'AlcoholLow', 1), (55, 'LiquorGrapefruit', 'AlcoholLow', 1), (56, 'Americano', 'AlcoholLow', 1), (57, 'Coffee', 'Soft', 1), (58, 'JuiceGrapefruit', 'Soft', 0); -- -------------------------------------------------------- -- -- Structure de la table `ingredientsfood` -- CREATE TABLE `ingredientsfood` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `type` enum('Meat','Vegetable','Spice','Other') NOT NULL, `have` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Déchargement des données de la table `ingredientsfood` -- INSERT INTO `ingredientsfood` (`id`, `name`, `type`, `have`) VALUES (1, 'Honey', 'Other', 1), (2, 'Salt', 'Other', 1), (3, 'Vinegar', 'Other', 1), (4, 'DuckBreast', 'Meat', 1), (5, 'Cumin', 'Spice', 1), (6, 'Curry', 'Spice', 1), (7, 'Water', 'Other', 1), (8, 'Potato', 'Vegetable', 1), (9, 'Carrot', 'Vegetable', 1), (10, 'Onion', 'Vegetable', 1), (11, 'Butter', 'Other', 1), (12, 'SourCream', 'Other', 1); -- -------------------------------------------------------- -- -- Structure de la table `recipes` -- CREATE TABLE `recipes` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `ingredients` varchar(1000) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Déchargement des données de la table `recipes` -- INSERT INTO `recipes` (`id`, `name`, `ingredients`) VALUES (1, 'Honey duck breast', 'DuckBreast;Honey;Vinegar;Salt'), (2, 'Carrot soup with cumin', 'Carrot;Cumin;Salt;Curry;Water;Potato;Onion;Butter;SourCream'); -- -- Index pour les tables déchargées -- -- -- Index pour la table `cocktails` -- ALTER TABLE `cocktails` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); -- -- Index pour la table `ingredients` -- ALTER TABLE `ingredients` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); -- -- Index pour la table `ingredientsfood` -- ALTER TABLE `ingredientsfood` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); -- -- Index pour la table `recipes` -- ALTER TABLE `recipes` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); -- -- AUTO_INCREMENT pour les tables déchargées -- -- -- AUTO_INCREMENT pour la table `cocktails` -- ALTER TABLE `cocktails` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=29; -- -- AUTO_INCREMENT pour la table `ingredients` -- ALTER TABLE `ingredients` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=59; -- -- AUTO_INCREMENT pour la table `ingredientsfood` -- ALTER TABLE `ingredientsfood` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT pour la table `recipes` -- ALTER TABLE `recipes` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 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
7bdc471b44b3347ca7b37e87c22100b572c51767
SQL
COMP4711DreamTeam/KnowledgeBase
/Database/resetDatabase.sql
UTF-8
2,207
3.6875
4
[ "MIT" ]
permissive
DROP TABLE IF EXISTS MESSAGES; DROP TABLE IF EXISTS CONVERSATIONS; DROP TABLE IF EXISTS POSTS; DROP TABLE IF EXISTS DISCUSSIONS; DROP TABLE IF EXISTS TOPICS; DROP TABLE IF EXISTS USER_LIKES; DROP TABLE IF EXISTS USERS; CREATE TABLE IF NOT EXISTS USERS ( ID int NOT NULL, PASSWORD varchar(255) NOT NULL, FIRST_NAME varchar(255) NOT NULL, LAST_NAME varchar(255) NOT NULL, EMAIL varchar(255) NOT NULL, PROFILE_IMAGE_URL varchar(255) NOT NULL, COUNTRY varchar(255) NOT NULL, DATE_OF_BIRTH DATETIME NOT NULL, ABOUT varchar(255) NOT NULL, PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS USER_LIKES ( USER_ID int NOT NULL, LIKED_USER_ID int NOT NULL, FOREIGN KEY(USER_ID) REFERENCES USERS(ID), FOREIGN KEY(LIKED_USER_ID) REFERENCES USERS(ID) ); CREATE TABLE IF NOT EXISTS TOPICS ( ID int NOT NULL, TOPIC varchar(255) NOT NULL, PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DISCUSSIONS ( ID int NOT NULL, TOPIC_ID int NOT NULL, USER_ID int NOT NULL, TITLE varchar(500) NOT NULL, DATE DATE NOT NULL, BODY varchar(2000) NOT NULL, PRIMARY KEY (ID), FOREIGN KEY (TOPIC_ID) REFERENCES TOPICS(ID), FOREIGN KEY (USER_ID) REFERENCES USERS(ID) ); CREATE TABLE IF NOT EXISTS POSTS ( ID int NOT NULL, DISCUSSION_ID int NOT NULL, USER_ID int NOT NULL, POST_BODY varchar(2000) NOT NULL, PRIMARY KEY (ID), FOREIGN KEY (DISCUSSION_ID) REFERENCES DISCUSSIONS(ID), FOREIGN KEY (USER_ID) REFERENCES USERS(ID) ); CREATE TABLE IF NOT EXISTS CONVERSATIONS ( ID int NOT NULL, USER_ID_1 int NOT NULL, USER_ID_2 int NOT NULL, DATE DATE NOT NULL, SUBJECT varchar(500) NOT NULL, `READ` TINYINT NOT NULL DEFAULT 0, PRIMARY KEY (ID), FOREIGN KEY (USER_ID_1) REFERENCES USERS(ID), FOREIGN KEY (USER_ID_2) REFERENCES USERS(ID) ); CREATE TABLE IF NOT EXISTS MESSAGES ( ID int NOT NULL, CONVERSATION_ID int NOT NULL, USER_ID int NOT NULL, DATE_TIME DATETIME NOT NULL, MESSAGE_BODY varchar(2000) NOT NULL, PRIMARY KEY (ID), FOREIGN KEY (CONVERSATION_ID) REFERENCES CONVERSATIONS(ID), FOREIGN KEY (USER_ID) REFERENCES USERS(ID) );
true
7d804da5a6d6af939a8d85f331f2214df01031d4
SQL
MatusKysel/bnbridge.exchange
/sdk/sql/setup.sql
UTF-8
1,968
3.375
3
[]
no_license
drop table if exists eth_accounts; create table eth_accounts ( uuid char(36) primary key, private_key varchar(128), address varchar(64), encr_key varchar(128), created timestamp ); drop table if exists bnb_accounts; create table bnb_accounts ( uuid char(36) primary key, public_key varchar(128), -- Inappropriate name, raw private_key of a bnb account encrypted by key `(KEY:dbPassword)` private_key varchar(512), address varchar(64), key_name varchar(64), -- dbPassword, a bip39 mnemonic encr_key varchar(128), created timestamp ); drop table if exists tokens; create table tokens ( uuid char(36) primary key, name varchar(64), symbol varchar(10), unique_symbol varchar(32), total_supply varchar(64), erc20_address varchar(64), mintable boolean, minimum_swap_amount varchar(32), fee_per_swap varchar(32), eth_account_uuid char(36), bnb_account_uuid char(36), processed boolean, listing_proposed boolean, listing_proposal_uuid char(36), listed boolean, created timestamp ); drop table if exists swaps; create table swaps ( uuid char(36) primary key, token_uuid char(36), client_account_uuid char(36), eth_address varchar(64), bnb_address varchar(64), amount varchar(32), deposit_transaction_hash varchar(128), transfer_transaction_hash varchar(128), processed boolean, created timestamp ); drop table if exists client_accounts; create table client_accounts ( uuid char(36) primary key, bnb_address varchar(64), client_eth_account_uuid char(36), encr_key varchar(512), created timestamp ); drop table if exists client_eth_accounts; create table client_eth_accounts ( uuid char(36) primary key, -- Inappropriate name, encrypted eth private key using `(KEY:dbPassword)` as encryption key private_key varchar(256), address varchar(64), -- dbPassword, a newly generated bip39 mnemonic for each created eth account encr_key varchar(128), created timestamp );
true
a8db82186efe4417e7882ae29c01ddf762cfde77
SQL
buddhascoopa/buddhascoopa-git
/pessoal/Scripts/Sql/Sql/rank3.SQL
UTF-8
247
4.125
4
[]
no_license
select a.sal, count(b.sal), sum((a.sal/c.total_sal)*100) from (select * from emp) a, (select distinct sal from emp) b, (select sum(sal) total_sal from emp) c where a.sal <= b.sal group by a.sal,a.empno order by sal desc /
true
57402803df120fa74147d7b756cd17cf090271ff
SQL
liuwenxuan013/DBS301-LAB
/lab8/L8_160678173_Liu.sql
UTF-8
6,334
4.25
4
[]
no_license
-- *********************** -- Name: Wenxuan Liu -- ID: 160678173 -- Date: 2019/03/14 -- Purpose: Lab 8 DBS301 -- *********************** --Q1--Display the names of the employees whose salary is the same as the lowest salaried employee in any department. --Q1--Solution-- SELECT first_name||' '||last_name AS "Name" FROM employees WHERE salary = ANY ( SELECT min(salary) FROM employees GROUP BY department_id ); --Q2--Display the names of the employee(s) whose salary is the lowest in each department. --Q2--Solution-- SELECT first_name||' '||last_name AS "Name" FROM employees WHERE (department_id,salary) IN ( SELECT department_id,min(salary) FROM employees GROUP BY department_id) ORDER BY last_name,first_name; --Q3--Give each of the employees in question 2 a $120 bonus --Q3--Solution-- SELECT first_name||' '||last_name AS "Name" ,to_char(salary+120,'$999,999.99') AS" new salary" FROM employees WHERE (department_id,salary) IN ( SELECT department_id,min(salary) FROM employees GROUP BY department_id) ORDER BY last_name,first_name; --Q4--Create a view named vwAllEmps that consists of all employees includes employee_id, last_name, salary, -- department_id, department_name, city and country (if applicable) --Q4--Solution-- CREATE VIEW vwAllEmps AS SELECT employee_id, last_name, salary, department_id, department_name, city, country_name FROM employees LEFT OUTER JOIN departments USING (department_id) LEFT OUTER JOIN locations USING (location_id) LEFT OUTER JOIN countries USING (country_id); --SELECT * FROM vwAllEmps; --DROP VIEW vwAllEmps; --Q5--1--Use the vwAllEmps view to: -- Display the employee_id, last_name, salary and city for all employees --Q5--1--Solution-- SELECT employee_id, last_name, to_char(salary,'$999,999.99') AS "Salary", city FROM vwAllEmps; --Q5--2--Display the total salary of all employees by city --Q5--2--Solution-- SELECT city,to_char(sum(salary),'$999,999.99') AS "Total salary" FROM vwAllEmps GROUP BY city ORDER BY sum(salary); --Q5--3--Increase the salary of the lowest paid employee(s) in each department by 120 --Q5--3--Solution-- UPDATE vwAllEmps SET salary= salary+120 WHERE (department_id,salary) IN ( SELECT department_id,min(salary) FROM vwAllEmps GROUP BY department_id); --to check the increase by the query below --SELECT employee_id,last_name,to_char(salary,'$999,999.99') AS "Salary" -- FROM vwAllEmps -- WHERE (department_id,salary) IN ( -- SELECT department_id,min(salary) -- FROM vwAllEmps -- GROUP BY department_id) -- ORDER BY last_name; --Q5--4--What happens if you try to insert an employee by providing values for all columns in this view? --Q5--4--Solution-- --Try to run this script: INSERT INTO vwAllEmps VALUES (208,'Laura',70000,111,'Office','Toronto','Canada'); --Generates a erroe because it cannot modify more than one base table through a join view, --the view is a sql script and the columns of the view belonging to more than one underlying table were either inserted into or updated. --Q5--5--Delete the employee named Vargas. Did it work? Show proof. --Q5--5--Solution-- --Delete from a view would work. it would actually delete data from the underlying table. DELETE FROM vwAllEmps WHERE last_name='Vargas'; --It works,run the above script then delete the record of 'Vargas'; --to check the result by select query below: --SELECT * FROM vwAllEmps WHERE upper(last_name)='VARGAS'; --Q6--Create a view named vwAllDepts that consists of all departments and includes department_id, -- department_name, city and country (if applicable) --Q6--Solution-- CREATE VIEW vwAllDepts AS SELECT department_id, department_name, city, country_name FROM departments LEFT OUTER JOIN locations USING (location_id) LEFT OUTER JOIN countries USING (country_id); --Q7--Use the vwAllDepts view to: --Q7--1--For all departments display the department_id, name and city --Q7--1--Solution-- SELECT department_id, department_name, city FROM vwAllDepts; --Q7--2--For each city that has departments located in it display the number of departments by city --Q7--2--Solution-- SELECT city,count(DISTINCT department_id) AS "Number of Dept." FROM vwAllDepts GROUP BY city ORDER BY "Number of Dept." DESC; --Q8--Create a view called vwAllDeptSumm that consists of all departments and includes for each department: -- department_id, department_name, number of employees, number of salaried employees, total salary of all employees. -- Number of Salaried must be different from number of employees. The difference is some get commission. --Q8--Solution create VIEW vwAllDeptSumm AS SELECT d.department_id, department_name, count(employee_id) AS "Emp#", count(employee_id)-count(commission_pct) AS "Salaried#", --the number of salaried employee is the only the number of employess who do not get commission sum(salary) AS "Total Salary" FROM departments d LEFT OUTER JOIN employees e ON d.department_id = e.department_id GROUP BY d.department_id,department_name; --DROP VIEW vwAllDeptSumm; --Q9-- Use the vwAllDeptSumm view to display department name and number of employees for departments -- that have more than the average number of employees select * from vwAllDeptSumm; --Q9--Solution-- SELECT department_name,"Emp#" FROM vwAllDeptSumm WHERE "Emp#" > (SELECT AVG("Emp#") FROM vwAllDeptSumm ); --Q10-- A) Use the GRANT statement to allow another student (Neptune account) to retrieve data for your employees -- table and to allow them to retrieve, insert and update data in your departments table. Show proof
 -- B) Use the REVOKE statement to remove permission for that student to insert and update data in -- your departments table --Q10--Solution-- GRANT SELECT ON employees TO dbs301_191b30; GRANT SELECT, INSERT, UPDATE ON departments TO dbs301_191b30; REVOKE INSERT,UPDATE ON departments FROM dbs301_191b30;--try to run using account dbs301_191b30;
true
791679e72b981da82ebaa939c9343ed56dd9d613
SQL
gangov/MySQL
/SubqueriesAndJoins/Lab/subqueries_and_joins_lab.sql
UTF-8
2,997
4.5625
5
[]
no_license
/* Lab: Subqueries and JOINs This document defines the lab assignments for MySQL Course @ Software University. You will use the soft_uni database to write queries for the following exercises. */ USE soft_uni; /* 1. Managers Write a query to retrieve information about the managers – id, full_name, deparment_id and department_name. Select the first 5 departments ordered by employee_id. Submit your queries using the “MySQL prepare DB and Run Queries” strategy. Example: employee_id full_name department_id department_name 3 Roberto Tamburello 10 Finance 4 Rob Walters 2 Tool Design 6 David Bradley 5 Purchasing 12 Terri Duffy 1 Engineering 21 Peter Krebs 8 Production Control */ SELECT employee_id, CONCAT(first_name, ' ', last_name) AS 'full_name', departments.department_id, name AS 'department_name' FROM employees JOIN departments ON employees.employee_id = departments.manager_id ORDER BY employee_id LIMIT 5; /* 2. Towns Addresses Write a query to get information about the addresses in the database, which are in San Francisco, Sofia or Carnation. Retrieve town_id, town_name, address_text. Order the result by town_id, then by address_id. Submit your queries using the “MySQL prepare DB and Run Queries” strategy. Example: town_id town_name address_text 9 San Fransisco 1234 Seaside Way 9 San Fransisco 5725 Glaze Drive 15 Carnation 1411 Ranch Drive … … … */ SELECT towns.town_id, name AS 'town_name', address_text FROM towns JOIN addresses ON towns.town_id = addresses.town_id WHERE (name = 'San Francisco' OR name = 'Sofia' OR name = 'Carnation') ORDER BY town_id, address_id; /* 3. Employees Without Managers Write a query to get information about employee_id, first_name, last_name, department_id and salary for all employees who don’t have a manager. Submit your queries using the “MySQL prepare DB and Run Queries” strategy. Example: employee_id first_name last_name department_id salary 109 Ken Sanchez 16 125 500 291 Svetlin Nakov 6 48 000 292 Martin Kulov 6 48 000 293 George Denchev 6 48 000 */ SELECT employee_id, first_name, last_name, department_id, salary FROM employees WHERE manager_id IS NULL; /* 4. Higher Salary Write a query to count the number of employees who receive salary higher than the average. Submit your queries using the “MySQL prepare DB and Run Queries” strategy. Example: count 88 */ SELECT COUNT(*) FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
true
61b2f65b240dc6216ea95f17688592f0b9548b63
SQL
marcosbarker/serratec.residencia
/serratec.desenvolvimentoAPI-Restful/dataBaseEconfigs/bibliotecaConfig/dataBase/ddl-biblioteca.sql
UTF-8
1,446
3.53125
4
[]
no_license
create database biblioteca; -- public.alunos definition -- Drop table -- DROP TABLE public.alunos; CREATE TABLE public.alunos ( numeromatriculaaluno serial NOT NULL, nome varchar(100) NOT NULL, datanascimento date NULL, cpf bpchar(11) NULL, logradouro varchar(100) NULL, numerologradouro varchar(10) NULL, complemento varchar(50) NULL, bairro varchar(50) NULL, cidade varchar(50) NULL, CONSTRAINT alunos_cpf_key UNIQUE (cpf), CONSTRAINT alunos_pkey PRIMARY KEY (numeromatriculaaluno) ); -- public.editora definition -- Drop table -- DROP TABLE public.editora; CREATE TABLE public.editora ( codigoeditora serial NOT NULL, nome varchar(50) NOT NULL, CONSTRAINT editora_pkey PRIMARY KEY (codigoeditora) ); -- public.emprestimo definition -- Drop table -- DROP TABLE public.emprestimo; CREATE TABLE public.emprestimo ( codigoemprestimo serial NOT NULL, numeromatriculaaluno int4 NOT NULL, codigolivro int4 NOT NULL, dataemprestimo date NOT NULL DEFAULT now(), dataentrega date NULL, valoremprestimo numeric(10,2) NULL, CONSTRAINT emprestimo_pkey PRIMARY KEY (codigoemprestimo) ); -- public.livros definition -- Drop table -- DROP TABLE public.livros; CREATE TABLE public.livros ( codigolivro serial NOT NULL, nomelivro varchar(120) NOT NULL, nomeautor varchar(100) NULL, datalancamento date NULL, codigoisbn int4 NOT NULL, codigoeditora int4 NOT NULL, CONSTRAINT livros_pkey PRIMARY KEY (codigolivro) );
true
e2e32f9e355118d6be34ea34a7b758011dc99da7
SQL
marcosmapl/uri-solutions
/09-sql/2617.sql
UTF-8
730
3.453125
3
[ "MIT" ]
permissive
/* URI Online Judge SQL | 2617 Provider Ajax SA Paulo R. Rodegheri BR Brasil https://www.urionlinejudge.com.br/judge/en/problems/view/2617 Timelimit: 1 The financial sector has encountered some problems in the delivery of one of our providers, the delivery of the products does not match the invoice. Your job is to display the name of the products and the name of the provider, for the products supplied by the provider 'Ajax SA'. @author Marcos Lima @profile https://www.urionlinejudge.com.br/judge/pt/profile/242402 @status Accepted @language PostgreSQL (psql 9.4.19) @time 0.003s @size 109 Bytes @submission 12/13/19, 11:32:56 PM */ select p.name, f.name from products p join providers f on p.id_providers = f.id where f.name = 'Ajax SA';
true
f20c3618ea70d60720d4d33664c6c511d1e042d4
SQL
killbill/killbill
/invoice/src/main/resources/org/killbill/billing/invoice/ddl.sql
UTF-8
10,635
3.84375
4
[ "Apache-2.0" ]
permissive
/*! SET default_storage_engine=INNODB */; DROP TABLE IF EXISTS invoice_tracking_ids; CREATE TABLE invoice_tracking_ids ( record_id serial unique, id varchar(36) NOT NULL, tracking_id varchar(128) NOT NULL, invoice_id varchar(36) NOT NULL, subscription_id varchar(36), unit_type varchar(255) NOT NULL, record_date date NOT NULL, is_active boolean default true, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, updated_by varchar(50) NOT NULL, updated_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE INDEX invoice_tracking_tenant_account_date_idx ON invoice_tracking_ids(tenant_record_id, account_record_id, record_date); CREATE INDEX invoice_tracking_invoice_id_idx ON invoice_tracking_ids(invoice_id); CREATE INDEX invoice_tracking_id_idx ON invoice_tracking_ids(id); DROP TABLE IF EXISTS invoice_tracking_id_history; CREATE TABLE invoice_tracking_id_history ( record_id serial unique, id varchar(36) NOT NULL, target_record_id bigint /*! unsigned */ not null, tracking_id varchar(128) NOT NULL, invoice_id varchar(36) NOT NULL, subscription_id varchar(36), unit_type varchar(255) NOT NULL, record_date date NOT NULL, is_active boolean default true, change_type varchar(6) NOT NULL, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, updated_by varchar(50) NOT NULL, updated_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE INDEX invoice_tracking_id_history_target_record_id ON invoice_tracking_id_history(target_record_id); CREATE INDEX invoice_tracking_id_history_tenant_record_id ON invoice_tracking_id_history(tenant_record_id); DROP TABLE IF EXISTS invoice_items; CREATE TABLE invoice_items ( record_id serial unique, id varchar(36) NOT NULL, type varchar(24) NOT NULL, invoice_id varchar(36) NOT NULL, account_id varchar(36) NOT NULL, child_account_id varchar(36), bundle_id varchar(36), subscription_id varchar(36), description varchar(255), product_name varchar(255), plan_name varchar(255), phase_name varchar(255), usage_name varchar(255), catalog_effective_date datetime, start_date date, end_date date, amount numeric(15,9) NOT NULL, rate numeric(15,9) NULL, currency varchar(3) NOT NULL, linked_item_id varchar(36), quantity decimal(18, 9), item_details text, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE UNIQUE INDEX invoice_items_id ON invoice_items(id); CREATE INDEX invoice_items_subscription_id ON invoice_items(subscription_id ASC); CREATE INDEX invoice_items_invoice_id ON invoice_items(invoice_id ASC); CREATE INDEX invoice_items_account_id ON invoice_items(account_id ASC); CREATE INDEX invoice_items_linked_item_id ON invoice_items(linked_item_id ASC); CREATE INDEX invoice_items_tenant_account_record_id ON invoice_items(tenant_record_id, account_record_id); DROP TABLE IF EXISTS invoice_item_history; CREATE TABLE invoice_item_history ( record_id serial unique, id varchar(36) NOT NULL, target_record_id bigint /*! unsigned */ not null, type varchar(24) NOT NULL, invoice_id varchar(36) NOT NULL, account_id varchar(36) NOT NULL, child_account_id varchar(36), bundle_id varchar(36), subscription_id varchar(36), description varchar(255), product_name varchar(255), plan_name varchar(255), phase_name varchar(255), usage_name varchar(255), catalog_effective_date datetime, start_date date, end_date date, amount numeric(15,9) NOT NULL, rate numeric(15,9) NULL, currency varchar(3) NOT NULL, linked_item_id varchar(36), quantity decimal(18, 9), item_details text, change_type varchar(6) NOT NULL, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE INDEX invoice_item_history_target_record_id ON invoice_item_history(target_record_id); CREATE INDEX invoice_item_history_tenant_record_id ON invoice_item_history(tenant_record_id); DROP TABLE IF EXISTS invoices; CREATE TABLE invoices ( record_id serial unique, id varchar(36) NOT NULL, account_id varchar(36) NOT NULL, invoice_date date NOT NULL, target_date date, currency varchar(3) NOT NULL, status varchar(15) NOT NULL DEFAULT 'COMMITTED', migrated bool NOT NULL, parent_invoice bool NOT NULL DEFAULT FALSE, grp_id varchar(36) NOT NULL, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE UNIQUE INDEX invoices_id ON invoices(id); CREATE INDEX invoices_account ON invoices(account_id ASC); CREATE INDEX invoices_tenant_account_record_id ON invoices(tenant_record_id, account_record_id); CREATE INDEX invoice_grp_id ON invoices(grp_id ASC); DROP TABLE IF EXISTS invoice_history; CREATE TABLE invoice_history ( record_id serial unique, id varchar(36) NOT NULL, target_record_id bigint /*! unsigned */ not null, account_id varchar(36) NOT NULL, invoice_date date NOT NULL, target_date date, currency varchar(3) NOT NULL, status varchar(15) NOT NULL DEFAULT 'COMMITTED', migrated bool NOT NULL, parent_invoice bool NOT NULL DEFAULT FALSE, grp_id varchar(36) NOT NULL, change_type varchar(6) NOT NULL, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE INDEX invoice_history_target_record_id ON invoice_history(target_record_id); CREATE INDEX invoice_history_tenant_record_id ON invoice_history(tenant_record_id); DROP TABLE IF EXISTS invoice_payments; CREATE TABLE invoice_payments ( record_id serial unique, id varchar(36) NOT NULL, type varchar(24) NOT NULL, invoice_id varchar(36) NOT NULL, payment_id varchar(36), payment_date datetime NOT NULL, amount numeric(15,9) NOT NULL, currency varchar(3) NOT NULL, processed_currency varchar(3) NOT NULL, payment_cookie_id varchar(255) DEFAULT NULL, linked_invoice_payment_id varchar(36) DEFAULT NULL, status varchar(50) NOT NULL, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE UNIQUE INDEX invoice_payments_id ON invoice_payments(id); CREATE INDEX invoice_payments_invoice_id ON invoice_payments(invoice_id); CREATE INDEX invoice_payments_reversals ON invoice_payments(linked_invoice_payment_id); CREATE INDEX invoice_payments_payment_id ON invoice_payments(payment_id); CREATE INDEX invoice_payments_payment_cookie_id ON invoice_payments(payment_cookie_id); CREATE INDEX invoice_payments_tenant_account_record_id ON invoice_payments(tenant_record_id, account_record_id); DROP TABLE IF EXISTS invoice_payment_history; CREATE TABLE invoice_payment_history ( record_id serial unique, id varchar(36) NOT NULL, target_record_id bigint /*! unsigned */ not null, type varchar(24) NOT NULL, invoice_id varchar(36) NOT NULL, payment_id varchar(36), payment_date datetime NOT NULL, amount numeric(15,9) NOT NULL, currency varchar(3) NOT NULL, processed_currency varchar(3) NOT NULL, payment_cookie_id varchar(255) DEFAULT NULL, linked_invoice_payment_id varchar(36) DEFAULT NULL, status varchar(50) NOT NULL, change_type varchar(6) NOT NULL, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE INDEX invoice_payment_history_target_record_id ON invoice_payment_history(target_record_id); CREATE INDEX invoice_payment_history_tenant_record_id ON invoice_payment_history(tenant_record_id); DROP TABLE IF EXISTS invoice_parent_children; CREATE TABLE invoice_parent_children ( record_id serial unique, id varchar(36) NOT NULL, parent_invoice_id varchar(36) NOT NULL, child_invoice_id varchar(36) NOT NULL, child_account_id varchar(36) NOT NULL, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE UNIQUE INDEX invoice_parent_children_id ON invoice_parent_children(id); CREATE INDEX invoice_parent_children_invoice_id ON invoice_parent_children(parent_invoice_id); CREATE INDEX invoice_parent_children_tenant_account_record_id ON invoice_parent_children(tenant_record_id, account_record_id); CREATE INDEX invoice_parent_children_child_invoice_id ON invoice_parent_children(child_invoice_id); DROP TABLE IF EXISTS invoice_billing_events; CREATE TABLE invoice_billing_events ( record_id serial unique, id varchar(36) NOT NULL, invoice_id varchar(36) NOT NULL, billing_events blob NOT NULL, created_by varchar(50) NOT NULL, created_date datetime NOT NULL, account_record_id bigint /*! unsigned */ not null, tenant_record_id bigint /*! unsigned */ not null default 0, PRIMARY KEY(record_id) ) /*! CHARACTER SET utf8 COLLATE utf8_bin */; CREATE UNIQUE INDEX invoice_billing_events_invoice_id ON invoice_billing_events(invoice_id); CREATE INDEX invoice_billing_events_tenant_account_record_id ON invoice_billing_events(tenant_record_id, account_record_id);
true
e993c2922d4c73f65bebe7ed77722006643969d8
SQL
Ckhronus/SistemaWebEscola
/build/web/sql/criação.sql
UTF-8
2,147
3.796875
4
[ "MIT" ]
permissive
drop database escola; create database escola; use escola; create table usuario( id int auto_increment primary key, nome varchar(45) not null, email varchar(45) not null, senha varchar(16) not null, tipo int not null ); create table apostila( id int primary key auto_increment, nome varchar(45) not null, quantidade int not null ); create table apostila_aluno( id int primary key auto_increment, id_apostila int not null, bloqueada boolean not null DEFAULT true, id_apostila_aluno int not null, CONSTRAINT fk_apostila FOREIGN KEY (id_apostila) REFERENCES apostila (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_apostila_aluno FOREIGN KEY (id_apostila_aluno) REFERENCES usuario (id) ON DELETE CASCADE ON UPDATE CASCADE ); create table parcela( id int primary key auto_increment, valor double(7,2) not null, vencimento date not null, pago boolean default false, data_pagamento date, id_aluno_parcela int, CONSTRAINT fk_aluno_parcela FOREIGN KEY (id_aluno_parcela) REFERENCES usuario (id) ON DELETE CASCADE ON UPDATE CASCADE ); create table qtd_parcelas_abertas( id int primary key auto_increment, total int ); create table curso( id int auto_increment primary key, nome varchar(45) not null, qtd_aulas int not null ); create table aula( id int auto_increment primary key, id_curso int not null, id_aluno_aula int not null, CONSTRAINT fk_id_curso FOREIGN KEY (id_curso) REFERENCES curso (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_aluno_aula FOREIGN KEY (id_aluno_aula) REFERENCES usuario (id) ON DELETE CASCADE ON UPDATE CASCADE ); create table faltas( id int auto_increment primary key, faltas int not null, data_falta date not null, id_aluno_faltas int not null, CONSTRAINT fk_aluno_faltas FOREIGN KEY (id_aluno_faltas) REFERENCES usuario (id) ON DELETE CASCADE ON UPDATE CASCADE );
true
78b5f3719f01e3ba7f20235ab33e492741def440
SQL
daveinnyc/various
/interview-questions/database-example.sql
UTF-8
1,451
4.03125
4
[ "MIT" ]
permissive
/* Development command line shortcuts: -- remove old DBs, create new one and display query results rm *db ; sqlite3 -column -header example.db < database-example.sql */ CREATE TABLE users( id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT, registerdate DATE ); CREATE TABLE orders( id INTEGER PRIMARY KEY, userid INTEGER, item TEXT ); INSERT INTO users (id, firstname, lastname, registerdate) VALUES (1, 'Sally', 'Lnamea', '2016-07-12'); INSERT INTO users (id, firstname, lastname, registerdate) VALUES (2, 'Bob', 'Lnamerb', '2016-07-06'); INSERT INTO users (id, firstname, lastname, registerdate) VALUES (3, 'Fred', 'Lnamec', '2016-07-07'); INSERT INTO users (id, firstname, lastname, registerdate) VALUES (4, 'Tom', 'Lnamed', '2016-07-08'); INSERT INTO users (id, firstname, lastname, registerdate) VALUES (5, 'Sally', 'Lnamee', '2016-07-09'); SELECT COUNT(firstname) AS count, registerdate FROM users WHERE firstname='Sally' GROUP BY registerdate; INSERT INTO orders (id, userid, item) VALUES (1, 2, "BB"); INSERT INTO orders (id, userid, item) VALUES (2, 3, "CC"); INSERT INTO orders (id, userid, item) VALUES (3, 5, "EE"); INSERT INTO orders (id, userid, item) VALUES (4, 1, "AA"); INSERT INTO orders (id, userid, item) VALUES (5, 3, "CC"); SELECT orders.id, users.firstname, users.lastname FROM orders LEFT JOIN users ON orders.userid = users.id ORDER BY orders.id;
true
d0713ef974ff9262e9feec39a45e13c0a89e5460
SQL
hiro1979/shika
/shika.sql
UTF-8
2,295
3.078125
3
[]
no_license
create table shikanavi(no int primary key auto_increment,koyou int,shokushu int,basho int,keitai int, name varchar(60),kyuuyo varchar(120),adress varchar(200),access varchar(200),title varchar(100),apeal varchar(500), motometeru varchar(500),shikaku int,time varchar(100),taiguu varchar(150),kyuuzitsu varchar(100),kyuuka varchar(100), ouboyouken varchar(200)); -- 検索画面では、職種(歯科助手、歯科衛生士、歯科技工士、歯科受付から選べる) -- 、場所(都道府県),雇用(正社員 パート)、サービス形態(クリニック、介護施設、デンタルエステ)から選べる -- 出力する求人詳細画面は、病院名、給与、住所、アクセス方法、求人タイトル、アピールポイント、求めている人物像、必要資格 -- 時間帯、待遇詳細、休日、長期休暇、応募条件が出てくる insert into shikanavi(koyou,shokushu,basho,keitai,name,kyuuyo,adress,access,title,apeal,motometeru,shikaku,time,taiguu,kyuuzitsu,kyuuka,ouboyouken) values(1,1,13,1,'サンプルクリニック','月18万円〜23万円','世田谷区南烏山2−5','京王線芦花公園駅より徒歩15分','最新設備に囲まれたオープニングクリニックにて歯科衛生士の募集','最新の設備と名医の元で最先端の歯科医学を学べます','歯科衛生士歴3年以上、35歳まで',1,'9時〜18時','社会保険完備、交通費支給,家賃補助あり','完全土日休み','夏休み3日、正月休み8日','歯科衛生士資格のある人'); insert into shikanavi(koyou,shokushu,basho,keitai,name,kyuuyo,adress,access,title,apeal,motometeru,shikaku,time,taiguu,kyuuzitsu,kyuuka,ouboyouken) values(1,1,13,1,'ゴージャスクリニック','月21万円〜23万円','世田谷区南烏山3−5','京王線芦花公園駅より徒歩5分','最新設備に囲まれたオープニングクリニックにて歯科衛生士の募集','最新の設備と名医の元で最先端の歯科医学を学べます','歯科衛生士歴3年以上、30歳まで',1,'9時〜18時','社会保険完備、交通費支給,家賃補助あり','完全土日休み','夏休み3日、正月休み8日','歯科衛生士資格のある人');
true
0c1473f66f6c887a51b67bd0e65a5e437b10badc
SQL
rishxbhhhh/DBMS-Project-Accounts-Payable-Database
/queries.sql
UTF-8
6,852
3.953125
4
[]
no_license
use dswproject; create table invoices( invoice_id int primary key AUTO_INCREMENT, vendor_id int not null, invoice_number VARCHAR(50) not null, invoice_date date not null, invoice_total decimal(9, 2) default 0, credit_total decimal(9, 2) DEFAULT 0, terms_id int not null, invoice_due_date date, payment_date date ); CREATE table terms( terms_id INT PRIMARY key AUTO_INCREMENT, terms_description VARCHAR(50) NOT NULL, terms_due_days int ); CREATE TABLE vendors( vendor_id int PRIMARY key AUTO_INCREMENT, vendor_name VARCHAR (50) not null, vendor_address1 VARCHAR (50) not null, vendor_address2 VARCHAR (50), vendor_city VARCHAR (50), vendor_state char(20), vendor_zip_code VARCHAR (20), vendor_phone VARCHAR (50), vendor_contact_last_name VARCHAR (50), vendor_contact_first_name VARCHAR (50), default_terms_id int not null, default_account_number int not null ); CREATE table general_ledger_accounts( account_number int PRIMARY KEY AUTO_INCREMENT, account_description VARCHAR (50) ); CREATE TABLE invoice_line_items( invoice_id int not null, invoice_sequence int not null, account_number int not null, line_item_amount decimal(9,2) not null, line_item_description VARCHAR (100), PRIMARY key(invoice_id, invoice_sequence), FOREIGN key(account_number) REFERENCES general_ledger_accounts (account_number) ); alter table invoices add constraint invoices_fk_vendors FOREIGN key (vendor_id) REFERENCES vendors (vendor_id), add constraint invoices_fk_terms FOREIGN key (terms_id) REFERENCES terms (terms_id); ALTER TABLE vendors add constraint vendors_fk_terms FOREIGN key (default_terms_id) REFERENCES terms (terms_id), add constraint vendors_fk_accounts FOREIGN key (default_account_number) REFERENCES general_ledger_accounts (account_number); /*1 trigger: BEFORE delete on terms table as it is foreign key constrained*/ DELIMITER // CREATE TRIGGER deleteTermsNotAllowed BEFORE DELETE ON terms FOR EACH ROW BEGIN signal sqlstate '49001' SET message_text = "DELETE on terms forbidden (foreign key restrained)!"; END // DELIMITER ; DELETE FROM terms; /*2 trigger: BEFORE delete on general Ledger Accounts table as it is foreign key constrained*/ DELIMITER // CREATE TRIGGER deleteAccountsNotAllowed BEFORE DELETE ON general_ledger_accounts FOR EACH ROW BEGIN signal sqlstate '49002' SET message_text = "DELETE on general_ledger_accounts forbidden (foreign key restrained)!"; END // DELIMITER ; DELETE FROM general_ledger_accounts; /*3 trigger: BEFORE INSERT on invoices table discount 10% if invoice_total > 100000 */ DELIMITER // CREATE TRIGGER updateInvoiceDiscount BEFORE INSERT ON invoices FOR EACH ROW BEGIN IF new.invoice_total > 100000 THEN SET new.invoice_total = (new.invoice_total)*0.9; END IF; END // DELIMITER ; INSERT INTO invoices(vendor_id,invoice_number,invoice_date,invoice_total,credit_total,terms_id,invoice_due_date,payment_date) VALUES (50,'499700','2012-08-23',1000099,48379.32,1,'2012-11-23','2012-09-23'); SELECT (invoice_total) FROM invoices WHERE vendor_id = 50 AND terms_id = 1; /*4 Procedure: To get names of all vendors*/ DELIMITER // CREATE PROCEDURE getvendors(INOUT vendorslist VARCHAR (10000)) BEGIN DECLARE isdone INT DEFAULT 0; DECLARE vendorname varchar(50); DECLARE vendorcursor CURSOR FOR SELECT vendor_name from vendors; DECLARE CONTINUE HANDLER FOR NOT FOUND SET isdone = 1; OPEN vendorcursor; vendorloop: LOOP FETCH vendorcursor INTO vendorname; IF isdone = 1 THEN LEAVE vendorloop; END IF; SET vendorslist = CONCAT(vendorname, ", ", vendorslist); END LOOP vendorloop; CLOSE vendorcursor; END // DELIMITER ; SET @vendorlist = ""; CALL getvendors(@vendorlist); SELECT @vendorlist; /*5: procedure to add late fees*/ -- there were no dates greater than current date so added a few update invoices SET payment_date = '2021-10-21' WHERE invoice_id IN (1,3,5,7,9); -- some invoice_total values were offlimit, thus update invoices SET invoice_total = 100000 WHERE invoice_total > 100000 -- glimpse of values about to be updated select invoice_id,invoice_total,'NOT updated payment' from invoices WHERE invoice_id IN (1,3,5,7,9); -- procedure DELIMITER // CREATE procedure addlatepayment() BEGIN DECLARE isdone INT DEFAULT 0; DECLARE invid INT DEFAULT 0; DECLARE invtotal INT DEFAULT 0; DECLARE oldpayment INT DEFAULT 0; DECLARE invpdate date DEFAULT 0; DECLARE invcursor CURSOR FOR SELECT invoice_id,payment_date,invoice_total FROM invoices; DECLARE CONTINUE HANDLER FOR NOT FOUND SET isdone = 1; OPEN invcursor; invloop: LOOP FETCH invcursor INTO invid,invpdate,invtotal; SET oldpayment = invtotal; IF isdone = 1 THEN LEAVE invloop; END IF; IF invpdate > CURDATE() THEN SET invtotal = invtotal * 1.05; UPDATE invoices SET invoice_total = invtotal WHERE invoice_id = invid; SELECT invoice_id as ID,oldpayment as PREVIOUS_TOTAL,invoice_total as UPDATED_TOTAL,'UPDATED' as STATUS from invoices WHERE invoice_id = invid; END IF; END LOOP invloop; SELECT 'Late dues added successfully'; CLOSE invcursor; END // DELIMITER ; -- calling PROCEDURE call addlatepayment(); --actually whole table is traversed but --here only those tuples shown which were actually updated /*6: procedure to show due payments*/ -- procedure DELIMITER // CREATE procedure showduepayments() BEGIN DECLARE isdone INT DEFAULT 0; DECLARE invid INT DEFAULT 0; DECLARE invtotal INT DEFAULT 0; DECLARE invpdate date DEFAULT 0; DECLARE cursorinv CURSOR FOR SELECT invoice_id,payment_date,invoice_total FROM invoices; DECLARE CONTINUE HANDLER FOR NOT FOUND SET isdone = 1; OPEN cursorinv; invloop: LOOP FETCH cursorinv INTO invid,invpdate,invtotal; IF isdone = 1 THEN LEAVE invloop; END IF; IF invpdate > CURDATE() THEN SELECT invoice_id as ID,payment_date,invoice_total as DUE_INVOICE,'PENDING' as STATUS from invoices WHERE invoice_id = invid; END IF; END LOOP invloop; CLOSE cursorinv; END // DELIMITER ; -- calling PROCEDURE call showduepayments(); /*7: Timestamp trigger to run procedure addlatepayment() daily once*/ -- to run scheduled events event organiser should be ON -- set it to 0 to turn it OFF SET GLOBAL event_scheduler = 1; -- sample event to see results if working CREATE EVENT updatepayment ON SCHEDULE EVERY 5 SECOND DO CALL dswproject.addlatepayment(); select invoice_id,invoice_total from invoices where invoice_id IN (1,3,5,7,9); -- repeat after 5 seconds select invoice_id,invoice_total from invoices where invoice_id IN (1,3,5,7,9); --dropping sample event drop event if exists updatepayment; -- actual event CREATE EVENT updatepayment ON SCHEDULE EVERY 1 DAY DO CALL dswproject.addlatepayment();
true
f81a4ea12ae19027afa155c85da31527d38d81d5
SQL
leeneko/SQL
/생산현황 조회.sql
UTF-8
1,630
3.234375
3
[]
no_license
CREATE PROCEDURE STD_PDM_O_120 ( IN FROMDT NVARCHAR(10), IN TODATE NVARCHAR(10), IN ITEMGRP NVARCHAR(20), IN WHSCODE NVARCHAR(20), IN ITEMCODE NVARCHAR(50) ) LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS BEGIN SELECT TO_NVARCHAR(A."PostDate", 'YYYY-MM-DD') AS "생산오더일L000Y", A."DocEntry" AS "문서번호L202Y", CASE A."Type" WHEN 'S' THEN '표준' WHEN 'P' THEN '판매' WHEN 'D' THEN '분해' END AS "유형L000Y", CASE A."Status" WHEN 'P' THEN '계획' WHEN 'R' THEN '릴리즈' WHEN 'L' THEN '마감' WHEN 'C' THEN '취소' END AS "상태L000Y", A."ItemCode" AS "제품코드L004Y", A."ProdName" AS "제품명L000Y", A."PlannedQty" AS "계획R000Y", TO_NVARCHAR(A."DueDate", 'YYYY-MM-DD') AS "생산일L000Y", A."CmpltQty" AS "완료R000Y", A."PlannedQty" - A."CmpltQty" AS "미결R000Y", B."ItemCode" AS "품목코드L004Y", C."ItemName" AS "품명L000Y", B."BaseQty" AS "기준수량R000Y", B."PlannedQty" AS "계획수량R000Y", B."PlannedQty" - B."IssuedQty" AS "미결수량R000Y", B."IssuedQty" AS "출고R000Y", B."wareHouse" AS "창고L000Y" FROM OWOR A INNER JOIN WOR1 B ON A."DocEntry" = B."DocEntry" INNER JOIN OITM C ON B."ItemCode" = C."ItemCode" INNER JOIN OITM D ON A."ItemCode" = D."ItemCode" WHERE TO_NVARCHAR(A."PostDate", 'YYYYMMDD') >= :FROMDT AND TO_NVARCHAR(A."PostDate", 'YYYYMMDD') <= :TODATE AND (D."ItmsGrpCod" = :ITEMGRP OR '' = :ITEMGRP) AND (A."Warehouse" = :WHSCODE OR '' = :WHSCODE) AND (A."ItemCode" = :ITEMCODE OR '' = :ITEMCODE); END; CALL STD_PDM_O_120 ('20200421', '20200421', '', '', '');
true
78eda2760743d0bf7fb982ea8d1836642e9a5ccf
SQL
Viking03265/Vincent-PHP
/backup080921.sql
UTF-8
1,755
3.109375
3
[]
no_license
-- -------------------------------------------------------- -- Host: localhost -- Server version: 10.4.20-MariaDB - mariadb.org binary distribution -- Server OS: Win64 -- HeidiSQL Version: 11.3.0.6295 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 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' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- Dumping database structure for bdd CREATE DATABASE IF NOT EXISTS `bdd` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `bdd`; -- Dumping structure for table bdd.choices CREATE TABLE IF NOT EXISTS `choices` ( `id` int(11) NOT NULL AUTO_INCREMENT, `option1` int(11) NOT NULL, `option2` int(11) NOT NULL, `option3` int(11) NOT NULL, `choice` int(11) NOT NULL, `time_stamp` datetime NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- Dumping data for table bdd.choices: ~0 rows (approximately) /*!40000 ALTER TABLE `choices` DISABLE KEYS */; INSERT INTO `choices` (`id`, `option1`, `option2`, `option3`, `choice`, `time_stamp`) VALUES (1, 0, 1, 1, 1, '2021-08-09 00:00:00'), (2, 1, 0, 1, 0, '2021-08-09 00:00:00'); /*!40000 ALTER TABLE `choices` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;
true
01ecf2ad52b52533c157ebf8cb13b6d18c8b683d
SQL
seanburns76/pbi_WeldShop_v2
/SeamlessOrders_v2.sql
UTF-8
196
2.96875
3
[]
no_license
select s.OpsDate, s.employee_id, s.workcenter, s.opseq, sum(DATEDIFF(second,s.start,s.stop)/60.0/60.0) as OpTime from vSeamlessToHour s group by s.OpsDate, s.employee_id, s.workcenter, s.opseq
true
65e9017ce35f20af516014e5fc4e290475bf9d5f
SQL
Sofiamnz/proyectofinalutn
/ProyecFinal/proyectofinal/proyecback/tablas_proyecback/persona.sql
UTF-8
2,191
2.96875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.3 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 04-01-2021 a las 18:42:58 -- Versión del servidor: 10.4.14-MariaDB -- Versión de PHP: 7.4.11 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 */; -- -- Base de datos: `cabañas` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `persona` -- CREATE TABLE `persona` ( `idPersona` int(11) NOT NULL, `nombre` varchar(45) COLLATE utf8_spanish2_ci NOT NULL, `apellido` varchar(45) COLLATE utf8_spanish2_ci NOT NULL, `email` varchar(45) COLLATE utf8_spanish2_ci NOT NULL, `telefono` int(11) NOT NULL, `ciudad` varchar(45) COLLATE utf8_spanish2_ci NOT NULL, `habilitado` tinyint(4) NOT NULL DEFAULT 1, `eliminado` tinyint(4) NOT NULL DEFAULT 0, `ts_create` timestamp NOT NULL DEFAULT current_timestamp(), `ts_update` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci; -- -- Volcado de datos para la tabla `persona` -- INSERT INTO `persona` (`idPersona`, `nombre`, `apellido`, `email`, `telefono`, `ciudad`, `habilitado`, `eliminado`, `ts_create`, `ts_update`) VALUES (1, 'Flor', 'Re', 'florencia.re@hotmail.com', 1234567, 'Santa Fe', 1, 0, '2021-01-04 17:37:33', '2021-01-04 17:37:33'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `persona` -- ALTER TABLE `persona` ADD PRIMARY KEY (`idPersona`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `persona` -- ALTER TABLE `persona` MODIFY `idPersona` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; 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
5e398a7aba71e25249a4051345eaacbf7a261fb8
SQL
readybytes/xius
/test/test/ui/sql/XiusScreenshotTest/testScreenshot.start.sql
UTF-8
841
2.640625
3
[]
no_license
DROP TABLE IF EXISTS `#__xius_info`;; CREATE TABLE IF NOT EXISTS `#__xius_info` ( `id` int(21) unsigned NOT NULL auto_increment, `labelName` varchar(250) NOT NULL, `params` text NOT NULL, `key` varchar(250) NOT NULL, `pluginParams` text NOT NULL, `pluginType` varchar(250) NOT NULL, `ordering` int(21) default NULL, `published` tinyint(1) NOT NULL default '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;; INSERT INTO `#__xius_info` (`id`, `labelName`, `params`, `key`, `pluginParams`, `pluginType`, `ordering`, `published`) VALUES (1, 'Gender', '', '2', '', 'Jsfields', 1, 1), (2, 'City', '', '11', '', 'Jsfields', 2, 1), (3, 'Country', '', '12', '', 'Jsfields', 3, 1), (4, 'Register Date', '', 'registerDate', '', 'Joomla', 4, 1), (5, 'Username', '', 'username', '', 'Joomla', 5, 1);;
true
53dd19b0fe6fc0664c6482ced60179e30d4975a3
SQL
AndreyIvshin/Tasks
/Task2/src/main/resources/db/migration/V1__init.sql
UTF-8
523
3.296875
3
[]
no_license
create sequence news_sequence start with 1 increment by 1; create sequence user_sequence start with 1 increment by 1; create table news_table ( news_id number(19,0) not null, news_brief varchar2(500 char), news_content long, news_date timestamp, news_title varchar2(100 char), primary key (news_id) ); create table user_table ( user_id number(19,0) not null, user_password varchar2(255 char), user_role varchar2(255 char), user_username varchar2(40 char), primary key (user_id) );
true
45c51ac2ae9dda95a40ce275b8f5f46c8c0c500a
SQL
sefouanedjamaa/Gestion-automatis-e-d-une-biblioth-que-universitaire
/ssa.sql
UTF-8
5,928
3.109375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: Aug 31, 2020 at 09:02 PM -- Server version: 5.7.26 -- PHP Version: 7.2.18 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `ssa` -- -- -------------------------------------------------------- -- -- Table structure for table `abonne` -- DROP TABLE IF EXISTS `abonne`; CREATE TABLE IF NOT EXISTS `abonne` ( `matricule` int(100) NOT NULL, `nom` char(40) NOT NULL, `prenom` char(40) NOT NULL, `email` varchar(40) NOT NULL, `telephone` int(12) NOT NULL, PRIMARY KEY (`matricule`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `abonne` -- INSERT INTO `abonne` (`matricule`, `nom`, `prenom`, `email`, `telephone`) VALUES (1, 'kk', 'kk', 'k@n.com', 188), (6, 'kkl', 'll', 'll@hgh.com', 454545), (7, 'ss', 'gg', 'h@k.com', 56), (785, 'dd', 'ddd', 'dd@j.com', 47); -- -------------------------------------------------------- -- -- Table structure for table `contact` -- DROP TABLE IF EXISTS `contact`; CREATE TABLE IF NOT EXISTS `contact` ( `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `subject` varchar(200) NOT NULL, `message` varchar(500) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `contact` -- INSERT INTO `contact` (`name`, `email`, `subject`, `message`) VALUES ('sefouaness', 'sefouanes@gmail.com', 'rien de rien ', 'juste un message'), ('sefouaness', 'sefouanes@gmail.com', 'rien de rien ', 'juste un message'), ('un conatct', 'dodo-1977@live.fr', 'ya pas', 'jhfsjkg'), ('raouf', 'sefouanes@gmail.com', 'kwana', 'uiiiiiiiiiiiiiiiiiiiiiidrj'), ('sollt', 'sefouanes@gmail.com', 'mmmmm', 'zegjkkkkkkkk'), ('anfel', 'sefouanes@gmail.com', 'php', 'livreeeeeeeeeee'), ('fatihhhhhhhhhhhh', 'fatima@gmail.com', 'un sjet dhhhhhhhhh', 'je suis bienjjjjj'), ('jkld', 'soso@gmail.com', 'jehzkjke', 'sober'), ('slt', 'slt@gmail.com', 'final', 'jkdsfdk'), ('', '', '', ''), ('', '', '', ''), ('', '', '', ''), ('', '', '', ''), ('', '', '', ''); -- -------------------------------------------------------- -- -- Table structure for table `docement` -- DROP TABLE IF EXISTS `docement`; CREATE TABLE IF NOT EXISTS `docement` ( `reference` varchar(100) NOT NULL, `titre` varchar(40) NOT NULL, `auteur` char(40) NOT NULL, `edition` char(40) NOT NULL, `anne` int(14) DEFAULT NULL, PRIMARY KEY (`reference`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `docement` -- INSERT INTO `docement` (`reference`, `titre`, `auteur`, `edition`, `anne`) VALUES ('1', 'hh', 'hh', 'hh', 1), ('111', 'ggg 47 kj', 'hyhyh', 'hyh', 2010), ('2', 'kk', 'kk', 'kk', 1111), ('3', 'mm', 'mm', 'mm', 3), ('55', 'gg', 'gg', 'gg', 1111), ('kjkkj', 'kjkj', 'kjkj', 'kjkjk', 1411); -- -------------------------------------------------------- -- -- Table structure for table `emprunt` -- DROP TABLE IF EXISTS `emprunt`; CREATE TABLE IF NOT EXISTS `emprunt` ( `refexmp` int(30) NOT NULL, `matricule` int(11) NOT NULL, `date_sortie` text NOT NULL, `date_rendu` text NOT NULL, KEY `matricule` (`matricule`), KEY `refexmp` (`refexmp`) USING BTREE, KEY `refexmp_2` (`refexmp`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `emprunt` -- INSERT INTO `emprunt` (`refexmp`, `matricule`, `date_sortie`, `date_rendu`) VALUES (666, 6, '1111/11/12', '1111/12/11'), (666, 7, 'jjjj', 'jjjj'); -- -------------------------------------------------------- -- -- Table structure for table `exomplaire` -- DROP TABLE IF EXISTS `exomplaire`; CREATE TABLE IF NOT EXISTS `exomplaire` ( `refexmp` int(100) NOT NULL, `refid` varchar(40) NOT NULL, `emplacement` varchar(20) NOT NULL, `etat` char(20) NOT NULL, `nbrexmp` int(10) NOT NULL, PRIMARY KEY (`refexmp`), KEY `refid` (`refid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `exomplaire` -- INSERT INTO `exomplaire` (`refexmp`, `refid`, `emplacement`, `etat`, `nbrexmp`) VALUES (1, '1', 'gg', 'gg', 0), (485, '111', 'mol54', 'bonne', 1), (666, '2', 'cote', 'bien', 11); -- -------------------------------------------------------- -- -- Table structure for table `penaliser` -- DROP TABLE IF EXISTS `penaliser`; CREATE TABLE IF NOT EXISTS `penaliser` ( `idm` int(20) NOT NULL, KEY `idm` (`idm`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `penaliser` -- INSERT INTO `penaliser` (`idm`) VALUES (1); -- -------------------------------------------------------- -- -- Table structure for table `utilisateur` -- DROP TABLE IF EXISTS `utilisateur`; CREATE TABLE IF NOT EXISTS `utilisateur` ( `nom_utilisateur` varchar(100) NOT NULL, `mot_de_passe` varchar(100) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `utilisateur` -- INSERT INTO `utilisateur` (`nom_utilisateur`, `mot_de_passe`) VALUES ('', ''), ('sefouane', 'djamaa'), ('soltane ', '1234'); -- -- Constraints for dumped tables -- -- -- Constraints for table `emprunt` -- ALTER TABLE `emprunt` ADD CONSTRAINT `emprunt_ibfk_1` FOREIGN KEY (`matricule`) REFERENCES `abonne` (`matricule`); -- -- Constraints for table `exomplaire` -- ALTER TABLE `exomplaire` ADD CONSTRAINT `exomplaire_ibfk_1` FOREIGN KEY (`refid`) REFERENCES `docement` (`reference`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `penaliser` -- ALTER TABLE `penaliser` ADD CONSTRAINT `penaliser_ibfk_1` FOREIGN KEY (`idm`) REFERENCES `abonne` (`matricule`); 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
67dd7eebb213b70b08223697c4f4da6cc336a437
SQL
george-sp/coding_bootcamp-java
/db_&_user_mgmt/00.sql_joins/exercise02.sql
UTF-8
269
3.25
3
[]
no_license
/* * Return the full names(first and last) of actors with "SON" in their last name, * ordered by their first name. */ SELECT sakila.actor.first_name, sakila.actor.last_name FROM sakila.actor WHERE sakila.actor.last_name LIKE '%son%' ORDER BY sakila.actor.first_name;
true
dc9e470283b790f665ed80547302c8880b60a1b5
SQL
altamira/visualstudio
/Sistema de Informação Altamira/EGISSQL.Database/dbo/Stored Procedures/Procs2/pr_pedido_venda_relatorio_nextel.sql
UTF-8
9,128
3.421875
3
[]
no_license
 ------------------------------------------------------------------------------- --sp_helptext pr_pedido_venda_relatorio_nextel ------------------------------------------------------------------------------- --pr_pedido_venda_relatorio_nextel ------------------------------------------------------------------------------- --GBS Global Business Solution Ltda 2008 ------------------------------------------------------------------------------- --Stored Procedure : Microsoft SQL Server 2000 --Autor(es) : Douglas de Paula Lopes --Banco de Dados : EgisAdmin ou Egissql --Objetivo : --Data : 06.08.2008 --Alteração : -- -- ------------------------------------------------------------------------------ create procedure pr_pedido_venda_relatorio_nextel @dt_Inicial datetime, @dt_Final datetime, @cd_pedido int, @filtro char(1) AS if @filtro = '1' begin select pvn.cd_pedido_venda, c.nm_fantasia_cliente, cast(pvn.cd_cliente as varchar) + ' - ' + rtrim(ltrim(c.nm_fantasia_cliente)) as cliente, rtrim(ltrim(c.nm_endereco_cliente)) + ' ' + rtrim(ltrim(c.cd_numero_endereco)) + ' ' + rtrim(ltrim(c.nm_bairro)) as endereco, max(c.cd_telefone) as telefone, pvn.cd_cliente, p.qt_peso_bruto, pvn.cd_status_pedido_nextel, spn.nm_status_pedido_nextel, v.nm_vendedor, pvn.cd_vendedor, pvn.cd_nota_saida, pvn.dt_pedido_venda_nextel, pvn.qt_dia_pagamento, p.nm_produto, p.cd_mascara_produto + ' - ' + rtrim(ltrim(p.nm_produto)) as nome_produto, p.vl_produto, p.pc_comissao_produto, case when isnull(p.pc_comissao_produto,0) <> 0 or isnull(p.pc_comissao_produto,0) <> null then -- Encontra o Valor do Percentual (isnull(pvn.vl_item_total_pedido,0) - (isnull(pvn.vl_item_total_pedido,0) - (isnull(pvn.vl_item_total_pedido,0) * (isnull(p.pc_comissao_produto,0) / 100)))) end as comissao, pvn.cd_produto, pvn.qt_itens_pedido_venda, pvn.vl_item_total_pedido, pvn.cd_tabela_preco, pvn.qt_item_pedido_venda_nextel, 0.00 as pc_comissao_item_pedido, 0.00 as pc_desconto_item_pedido, '' as sg_unidade_medida, cast(null as datetime) as dt_credito_pedido_venda, 0 as cd_item_pedido_venda from pedido_venda_nextel pvn with(nolock) left outer join produto p with(nolock) on p.cd_produto = pvn.cd_produto left outer join cliente c with(nolock) on c.cd_cliente = pvn.cd_cliente left outer join vendedor v with(nolock) on v.cd_vendedor = pvn.cd_vendedor left outer join status_pedido_nextel spn with(nolock) on spn.cd_status_pedido_nextel = pvn.cd_status_pedido_nextel where pvn.dt_pedido_venda_nextel between @dt_Inicial and @dt_Final group by pvn.cd_pedido_venda, c.nm_fantasia_cliente, pvn.cd_cliente, p.qt_peso_bruto, pvn.cd_status_pedido_nextel, spn.nm_status_pedido_nextel, v.nm_vendedor, pvn.cd_vendedor, pvn.cd_nota_saida, pvn.dt_pedido_venda_nextel, pvn.qt_dia_pagamento, p.nm_produto, p.vl_produto, p.pc_comissao_produto, pvn.cd_produto, pvn.qt_itens_pedido_venda, pvn.vl_item_total_pedido, pvn.cd_tabela_preco, pvn.qt_item_pedido_venda_nextel, c.nm_endereco_cliente, c.cd_numero_endereco, c.nm_bairro, p.cd_mascara_produto end else if @filtro = '2' begin select pvn.cd_pedido_venda, c.nm_fantasia_cliente, cast(pvn.cd_cliente as varchar) + ' - ' + rtrim(ltrim(c.nm_fantasia_cliente)) as cliente, rtrim(ltrim(c.nm_endereco_cliente)) + ' ' + rtrim(ltrim(c.cd_numero_endereco)) + ' ' + rtrim(ltrim(c.nm_bairro)) as endereco, max(c.cd_telefone) as telefone, pvn.cd_cliente, p.qt_peso_bruto, pvn.cd_status_pedido_nextel, spn.nm_status_pedido_nextel, v.nm_vendedor, pvn.cd_vendedor, pvn.cd_nota_saida, pvn.dt_pedido_venda_nextel, pvn.qt_dia_pagamento, p.nm_produto, p.cd_mascara_produto + ' - ' + rtrim(ltrim(p.nm_produto)) as nome_produto, p.vl_produto, p.pc_comissao_produto, case when isnull(p.pc_comissao_produto,0) <> 0 or isnull(p.pc_comissao_produto,0) <> null then -- Encontra o Valor do Percentual (isnull(pvn.vl_item_total_pedido,0) - (isnull(pvn.vl_item_total_pedido,0) - (isnull(pvn.vl_item_total_pedido,0) * (isnull(p.pc_comissao_produto,0) / 100)))) end as comissao, pvn.cd_produto, pvn.qt_itens_pedido_venda, pvn.vl_item_total_pedido, pvn.cd_tabela_preco, pvn.qt_item_pedido_venda_nextel, 0.00 as pc_comissao_item_pedido, 0.00 as pc_desconto_item_pedido, '' as sg_unidade_medida, cast(null as datetime) as dt_credito_pedido_venda, 0 as cd_item_pedido_venda from pedido_venda_nextel pvn with(nolock) left outer join produto p with(nolock) on p.cd_produto = pvn.cd_produto left outer join cliente c with(nolock) on c.cd_cliente = pvn.cd_cliente left outer join vendedor v with(nolock) on v.cd_vendedor = pvn.cd_vendedor left outer join status_pedido_nextel spn with(nolock) on spn.cd_status_pedido_nextel = pvn.cd_status_pedido_nextel where pvn.cd_pedido_venda = @cd_pedido group by pvn.cd_pedido_venda, c.nm_fantasia_cliente, pvn.cd_cliente, p.qt_peso_bruto, pvn.cd_status_pedido_nextel, spn.nm_status_pedido_nextel, v.nm_vendedor, pvn.cd_vendedor, pvn.cd_nota_saida, pvn.dt_pedido_venda_nextel, pvn.qt_dia_pagamento, p.nm_produto, p.vl_produto, p.pc_comissao_produto, pvn.cd_produto, pvn.qt_itens_pedido_venda, pvn.vl_item_total_pedido, pvn.cd_tabela_preco, pvn.qt_item_pedido_venda_nextel, c.nm_endereco_cliente, c.cd_numero_endereco, c.nm_bairro, p.cd_mascara_produto end else select pvn.cd_pedido_venda, c.nm_fantasia_cliente, cast(pvn.cd_cliente as varchar) + ' - ' + rtrim(ltrim(c.nm_fantasia_cliente)) as cliente, rtrim(ltrim(c.nm_endereco_cliente)) + ' ' + rtrim(ltrim(c.cd_numero_endereco)) + ' ' + rtrim(ltrim(c.nm_bairro)) as endereco, max(c.cd_telefone) as telefone, pvn.cd_cliente, p.qt_peso_bruto, pvn.cd_status_pedido_nextel, spn.nm_status_pedido_nextel, v.nm_vendedor, pvn.cd_vendedor, pvn.cd_nota_saida, pvn.dt_pedido_venda_nextel, pvn.qt_dia_pagamento, p.nm_produto, p.cd_mascara_produto + ' - ' + rtrim(ltrim(p.nm_produto)) as nome_produto, p.vl_produto, p.pc_comissao_produto, case when isnull(p.pc_comissao_produto,0) <> 0 or isnull(p.pc_comissao_produto,0) <> null then -- Encontra o Valor do Percentual (isnull(pvn.vl_item_total_pedido,0) - (isnull(pvn.vl_item_total_pedido,0) - (isnull(pvn.vl_item_total_pedido,0) * (isnull(p.pc_comissao_produto,0) / 100)))) end as comissao, pvn.cd_produto, pvn.qt_itens_pedido_venda, pvn.vl_item_total_pedido, pvn.cd_tabela_preco, pvn.qt_item_pedido_venda_nextel, 0.00 as pc_comissao_item_pedido, 0.00 as pc_desconto_item_pedido, '' as sg_unidade_medida, cast(null as datetime) as dt_credito_pedido_venda, 0 as cd_item_pedido_venda from pedido_venda_nextel pvn with(nolock) left outer join produto p with(nolock) on p.cd_produto = pvn.cd_produto left outer join cliente c with(nolock) on c.cd_cliente = pvn.cd_cliente left outer join vendedor v with(nolock) on v.cd_vendedor = pvn.cd_vendedor left outer join status_pedido_nextel spn with(nolock) on spn.cd_status_pedido_nextel = pvn.cd_status_pedido_nextel where pvn.dt_pedido_venda_nextel between @dt_Inicial and @dt_final and pvn.cd_pedido_venda = @cd_pedido group by pvn.cd_pedido_venda, c.nm_fantasia_cliente, pvn.cd_cliente, p.qt_peso_bruto, pvn.cd_status_pedido_nextel, spn.nm_status_pedido_nextel, v.nm_vendedor, pvn.cd_vendedor, pvn.cd_nota_saida, pvn.dt_pedido_venda_nextel, pvn.qt_dia_pagamento, p.nm_produto, p.vl_produto, p.pc_comissao_produto, pvn.cd_produto, pvn.qt_itens_pedido_venda, pvn.vl_item_total_pedido, pvn.cd_tabela_preco, pvn.qt_item_pedido_venda_nextel, c.nm_endereco_cliente, c.cd_numero_endereco, c.nm_bairro, p.cd_mascara_produto
true
b36c9fe615c7c8dd124245788be751f8060db715
SQL
kunil/TE_PROJECT
/finalT87.sql
UTF-8
13,684
3.203125
3
[]
no_license
-- MySQL dump 10.13 Distrib 8.0.12, for Linux (x86_64) -- -- Host: localhost Database: trendz -- ------------------------------------------------------ -- Server version 8.0.12 /*!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 */; SET NAMES utf8mb4 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Temporary view structure for view `V1` -- DROP TABLE IF EXISTS `V1`; /*!50001 DROP VIEW IF EXISTS `V1`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8mb4; /*!50001 CREATE VIEW `V1` AS SELECT 1 AS `fname`, 1 AS `lname`, 1 AS `cust_id`, 1 AS `sum(amount)`*/; SET character_set_client = @saved_cs_client; -- -- Table structure for table `admin` -- DROP TABLE IF EXISTS `admin`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `admin` ( `admin_id` int(11) NOT NULL, `name` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, PRIMARY KEY (`admin_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `admin` -- LOCK TABLES `admin` WRITE; /*!40000 ALTER TABLE `admin` DISABLE KEYS */; INSERT INTO `admin` VALUES (1,'tanish','tanish'),(2,'pratik','pratik'),(3,'riya','riya'); /*!40000 ALTER TABLE `admin` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `bill` -- DROP TABLE IF EXISTS `bill`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `bill` ( `bill_id` int(11) NOT NULL AUTO_INCREMENT, `cust_id` int(11) NOT NULL, `date` date DEFAULT NULL, `time` varchar(20) DEFAULT NULL, `amount` varchar(20) DEFAULT NULL, `admin_id` int(11) DEFAULT NULL, PRIMARY KEY (`bill_id`), KEY `cust_id` (`cust_id`), KEY `admin_id` (`admin_id`), CONSTRAINT `bill_ibfk_1` FOREIGN KEY (`cust_id`) REFERENCES `customer` (`cust_id`), CONSTRAINT `bill_ibfk_2` FOREIGN KEY (`admin_id`) REFERENCES `admin` (`admin_id`) ) ENGINE=InnoDB AUTO_INCREMENT=117 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `bill` -- LOCK TABLES `bill` WRITE; /*!40000 ALTER TABLE `bill` DISABLE KEYS */; INSERT INTO `bill` VALUES (101,1,'2018-10-29','07:41:01 AM','89492',3),(102,2,'2018-10-29','07:42:24 AM','47497',3),(103,3,'2018-10-29','07:44:59 AM','40992',3),(104,4,'2018-10-29','10:53:10 AM','121995',3),(105,5,'2018-11-03','23:40:51 PM','122397',1),(106,1,NULL,NULL,NULL,1),(107,1,'2019-03-19','22:18:15 PM','157994',3),(108,6,'2019-03-19','22:38:17 PM',NULL,1),(110,6,'2019-03-20','11:54:58 AM','398980',1),(111,6,NULL,NULL,NULL,1),(116,1,'2019-07-08','17:51:14 PM','100000',3); /*!40000 ALTER TABLE `bill` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `customer` -- DROP TABLE IF EXISTS `customer`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `customer` ( `cust_id` int(11) NOT NULL AUTO_INCREMENT, `fname` varchar(20) DEFAULT NULL, `lname` varchar(20) DEFAULT NULL, `gender` varchar(20) DEFAULT NULL, `number` bigint(20) NOT NULL, `email` varchar(20) DEFAULT NULL, `locality` varchar(50) DEFAULT NULL, `city` varchar(15) DEFAULT NULL, `state` varchar(20) DEFAULT NULL, `birthdate` date DEFAULT NULL, `admin_id` int(11) DEFAULT NULL, PRIMARY KEY (`cust_id`), KEY `admin_id` (`admin_id`), CONSTRAINT `customer_ibfk_1` FOREIGN KEY (`admin_id`) REFERENCES `admin` (`admin_id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `customer` -- LOCK TABLES `customer` WRITE; /*!40000 ALTER TABLE `customer` DISABLE KEYS */; INSERT INTO `customer` VALUES (1,'kunil','kothari','Male',8552940134,'kunil9@gmail.com','Hyde park','Mumbai','Arunachal Pradesh','2018-10-16',2),(2,'riya','loya','Female',7741068050,'riya.loya@gmail.com','Amar Cottages','Pune','Assam','2018-10-03',3),(3,'Pratik','Mehta','Male',8237358545,'pratik9@gmail.com','HermesHeritage','Banglore','Assam','2018-10-14',3),(4,'riya','loya','Female',9850453050,'riya.loya@gmail.com','hadapsar','Mumbai','Andhra Pradesh','2018-10-09',3),(5,'bhavini','kothari','Female',9545966615,'bhavini@gmail.com','hyde park','Pune','Assam','2018-11-15',1),(6,'Tanish','Shah','Male',9172324321,'tanish2110@gmail.com','Mukundnagar','Pune','Assam','1998-10-21',1),(7,'Tanish','Shah','Male',8208083770,'tanish231@gmail.com','Mukunnnagar','Pune','Maharashtra','2017-03-16',1); /*!40000 ALTER TABLE `customer` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `inventory` -- DROP TABLE IF EXISTS `inventory`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `inventory` ( `item_id` int(11) NOT NULL, `type` varchar(20) DEFAULT NULL, `name` varchar(20) DEFAULT NULL, `CP` int(11) DEFAULT NULL, `SP` int(11) DEFAULT NULL, `stock` int(11) DEFAULT NULL, `admin_id` int(11) DEFAULT NULL, PRIMARY KEY (`item_id`), KEY `admin_id` (`admin_id`), CONSTRAINT `inventory_ibfk_1` FOREIGN KEY (`admin_id`) REFERENCES `admin` (`admin_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `inventory` -- LOCK TABLES `inventory` WRITE; /*!40000 ALTER TABLE `inventory` DISABLE KEYS */; INSERT INTO `inventory` VALUES (100,'Sofa Set','Santiago Blue Sofa',17999,100000,14,3),(101,'Sofa Set','Segur Wood SofaSet',23499,40799,2,2),(200,'Bedroom Set','Taro Queen Size Bed',20499,47497,9,3),(300,'Wadrobes','Nariko',15999,38997,8,1),(400,'Dining Set','Tempura Dining Set',15999,38997,8,1),(500,'Artefacts','Polyresin Monk',249,1995,9,2),(600,'Bedroom Set','abc',13000,40000,4,1); /*!40000 ALTER TABLE `inventory` ENABLE KEYS */; UNLOCK TABLES; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8mb4 */ ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `profits` AFTER INSERT ON `inventory` FOR EACH ROW begin declare p float; declare id int; set p=new.SP-new.CP; select max(item_id) into id from inventory; insert into profit values(id,p); end */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `link` -- DROP TABLE IF EXISTS `link`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `link` ( `id` int(11) DEFAULT NULL, `bill_id` int(11) DEFAULT NULL, KEY `bill_id` (`bill_id`), KEY `id` (`id`), CONSTRAINT `link_ibfk_3` FOREIGN KEY (`bill_id`) REFERENCES `bill` (`bill_id`) ON DELETE CASCADE, CONSTRAINT `link_ibfk_4` FOREIGN KEY (`id`) REFERENCES `product` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `link` -- LOCK TABLES `link` WRITE; /*!40000 ALTER TABLE `link` DISABLE KEYS */; INSERT INTO `link` VALUES (3,101),(9,103),(10,104),(12,104),(13,105),(15,107),(16,107),(19,110),(22,116); /*!40000 ALTER TABLE `link` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `product` -- DROP TABLE IF EXISTS `product`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `product` ( `id` int(11) NOT NULL AUTO_INCREMENT, `pid` int(11) DEFAULT NULL, `prod_name` varchar(20) DEFAULT NULL, `prod_type` varchar(20) DEFAULT NULL, `mrp` float DEFAULT NULL, `qty` int(11) DEFAULT NULL, `total_cost` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `pid` (`pid`), CONSTRAINT `product_ibfk_2` FOREIGN KEY (`pid`) REFERENCES `inventory` (`item_id`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `product` -- LOCK TABLES `product` WRITE; /*!40000 ALTER TABLE `product` DISABLE KEYS */; INSERT INTO `product` VALUES (1,100,'Santiago Blue Sofa','Sofa Set',40000,1,40000),(2,100,'Santiago Blue Sofa','Sofa Set',40000,1,40000),(3,100,'Santiago Blue Sofa','Sofa Set',40000,1,40000),(9,500,'Polyresin Monk','Artefacts',1995,1,1995),(10,100,'Santiago Blue Sofa','Sofa Set',60000,2,120000),(12,500,'Polyresin Monk','Artefacts',1995,1,1995),(13,101,'Segur Wood SofaSet','Sofa Set',40799,3,122397),(15,100,'Santiago Blue Sofa','Sofa Set',80000,1,80000),(16,300,'Nariko','Wadrobes',38997,2,77994),(19,101,'Segur Wood SofaSet','Sofa Set',40799,5,203995),(22,100,'Santiago Blue Sofa','Sofa Set',100000,1,100000); /*!40000 ALTER TABLE `product` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `profit` -- DROP TABLE IF EXISTS `profit`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `profit` ( `profit_id` int(11) NOT NULL, `profit` int(11) DEFAULT NULL, PRIMARY KEY (`profit_id`), CONSTRAINT `profit_ibfk_1` FOREIGN KEY (`profit_id`) REFERENCES `inventory` (`item_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `profit` -- LOCK TABLES `profit` WRITE; /*!40000 ALTER TABLE `profit` DISABLE KEYS */; INSERT INTO `profit` VALUES (100,19001),(101,17300),(200,26998),(300,23198),(400,22998),(500,1746),(600,27000); /*!40000 ALTER TABLE `profit` ENABLE KEYS */; UNLOCK TABLES; -- -- Temporary view structure for view `t` -- DROP TABLE IF EXISTS `t`; /*!50001 DROP VIEW IF EXISTS `t`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8mb4; /*!50001 CREATE VIEW `t` AS SELECT 1 AS `cust_id`, 1 AS `fname`, 1 AS `lname`, 1 AS `sum(amount)`*/; SET character_set_client = @saved_cs_client; -- -- Final view structure for view `V1` -- /*!50001 DROP VIEW IF EXISTS `V1`*/; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; /*!50001 SET character_set_client = utf8mb4 */; /*!50001 SET character_set_results = utf8mb4 */; /*!50001 SET collation_connection = utf8mb4_0900_ai_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ /*!50001 VIEW `V1` AS select `customer`.`fname` AS `fname`,`customer`.`lname` AS `lname`,`customer`.`cust_id` AS `cust_id`,sum(`bill`.`amount`) AS `sum(amount)` from (`customer` join `bill`) where (`customer`.`cust_id` = `bill`.`cust_id`) group by `customer`.`cust_id` having (sum(`bill`.`amount`) > 70000) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; -- -- Final view structure for view `t` -- /*!50001 DROP VIEW IF EXISTS `t`*/; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; /*!50001 SET character_set_client = utf8mb4 */; /*!50001 SET character_set_results = utf8mb4 */; /*!50001 SET collation_connection = utf8mb4_0900_ai_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ /*!50001 VIEW `t` AS select `customer`.`cust_id` AS `cust_id`,`customer`.`fname` AS `fname`,`customer`.`lname` AS `lname`,sum(`bill`.`amount`) AS `sum(amount)` from (`customer` join `bill` on((`bill`.`cust_id` = `customer`.`cust_id`))) group by `customer`.`cust_id` having (sum(`bill`.`amount`) > '90') */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-07-08 17:59:12
true
521d09bf0fea72996ec62face16f1ac524925cef
SQL
luxin763323387/springboot
/springboot_mybatis_demo/db/t_user.sql
UTF-8
1,241
2.71875
3
[]
no_license
/* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Version : 50724 Source Host : localhost:3306 Source Database : test Target Server Type : MYSQL Target Server Version : 50724 File Encoding : 65001 Date: 2019-01-26 11:43:38 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for t_user -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `phone` varchar(255) NOT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB AUTO_INCREMENT=1008 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_user -- ---------------------------- INSERT INTO `t_user` VALUES ('1001', 'asdada', '123456', '123456'); INSERT INTO `t_user` VALUES ('1002', 'asdada', '123456', '123456'); INSERT INTO `t_user` VALUES ('1003', '22', '123456', '123456'); INSERT INTO `t_user` VALUES ('1004', '22', '123456', '123456'); INSERT INTO `t_user` VALUES ('1005', '22', '123456', '123456'); INSERT INTO `t_user` VALUES ('1006', '22', '123456', '123456'); INSERT INTO `t_user` VALUES ('1007', '22', '123456', '123456');
true
5472dfdb9bdb07c4a8dcb29ee417b8c470ca38d6
SQL
George-Price/Data_Wrangling_Project_and_Tasks
/Final_Project/Final.sql
UTF-8
1,028
4.25
4
[]
no_license
/* Number Two */ /* Merge Tables */ SELECT * into [gprice].[q2] FROM gprice.Demographics INNER JOIN dbo.Conditions ON gprice.Demographics.ID = dbo.Conditions.tri_patientid INNER JOIN dbo.TextMessages ON gprice.Demographics.ID = dbo.TextMessages.tri_contactId AND gprice.Demographics.ID = dbo.Conditions.tri_patientid /* Print 10 rows */ select top 10 * from gprice.q2 ORDER BY NEWID() /* Change TextSentDate to date format */ alter table gprice.q2 alter column TextSentDate DATE /* Create a table that contains the max textsentdate from merged table */ SELECT merged.* INTO gprice.q2max FROM gprice.q2 merged INNER JOIN ( SELECT tri_contactId, MAX(TextSentDate) AS MaxTextSentDate FROM gprice.joined GROUP BY tri_contactId) maxgroup ON merged.tri_contactID = maxgroup.tri_contactId AND merged.TextSentDate = maxgroup.MaxTextSentDate /* Check count to ensure not all rows are being saved */ SELECT COUNT (TextSentDate) FROM gprice.q2max /* Print 10 rows */ select top 10 * from gprice.q2max ORDER BY NEWID()
true
f68c61821c2b7fca9b9c02c8ea270ea9b16af8de
SQL
SeongJunKang/BitCamp-data-project
/BitcampJava80/SJ/db01/test02_TableType.sql
UTF-8
4,901
4.28125
4
[]
no_license
/* * not null , unique , default , primary key */ 1.테이블 생성 drop table test01; create table test01( tno int, name char(5) ); 2.값 입력 /* * 컬럼을 지정하지 않는 경우, * create table에 선언된 순서대로 모든 컬럼의 값을 지정해야 한다. */ insert into 테이블명(컬럼명, 컬럼명,...) values(값,값,...); insert into test01 values('hong',1); /*tno 값이 0이 됨*/ insert into test01 values(2,'park'); /* ok */ insert into test01 values(3); /* Fail */ /* * 특정 컬럼의 값 입력을 생략한 경우, * null 값으로 설정된다. */ insert into test01(tno) values(3); insert into test01(name) values("홍길동"); 3. 특정 컬럼을 필수 입력 컬럼으로 만드는 방법. => 컬럼선언에 not null 선언을 붙인다. => MySQL 의 경우 not null 컬럼의 값을 생략하면 그 타입의 기본 값이 저장된다. int : 0 , char : 빈문자열 예 ) tno 컬럼을 필수 입력 컬럼으로 만든다. drop table test01; create table test01( tno int unique, name char(5) not null ); 4. 특정 컬럼의 값이 중복되지 않게 만드는 방법. => unique 옵션을 붙인다. => 값이 중복되면 오류 발생. 값이 없으면 중복 여부를 검사하지 않는다. insert into test01(name,tno) values('홍길동',1); insert into test01(name,tno) values('임꺽정',2); insert into test01(name,tno) values('이순신',1); /*값 중복 오류*/ insert into test01(name) values('이순신'); /*Null 값은 값의 중복으로 취급 안하기 때문에 허용*/ insert into test01(name) values('이순신'); 5. 특정 컬럼의 값이 중복되지 않게 만드는 방법. => unique 옵션을 붙인다. > 컬럼선언에 not null 선언을 붙인다. drop table test01; create table test01( tno int unique not null, name char(5) not null ); insert into test01(name,tno) values('홍길동',1); insert into test01(name,tno) values('임꺽정',2); insert into test01(name,tno) values('이순신',1); /*값 중복 오류*/ insert into test01(name) values('이순신'); /*첫번째는 int의 기본값인 0이 들어간다.*/ insert into test01(name) values('이순신'); /*두번째도 0이 들어가기 때문에 중복으로 오류발생*/ 6. 값을 입력하지 않으면 지정한 값으로 자동으로 넣는 방법 => default 옵션을 사용한다. create table test01( tno int unique not null, name char(5) default '홍길동' ); insert into test01(tno) values(3); 7.unique 중에서 data를 구분할 때 사용할 컬럼은 값이 없어서는 안된다. => unique 에 not null 을 추가하라. drop table test01; create table test01( tno int unique, name char(5) default '홍길동', email char(20) unique ); insert into test01(name,tno) values('홍길동',1); insert into test01(name,tno) values('임꺽정',2); insert into test01(name,email) values('이순신','lee@'); insert into test01(name,email) values('강감찬','kang@'); insert into test01(name,tno) values('임꺽정',2); insert into test01(name,email) values('임꺽정','leem@'); insert into test01(name,email) values('강감찬','kang@0'); insert into test01(name,tno) values('강감찬',3); insert into test01(name) values('강감찬'); /*이름이 같기 때문에 강감찬 중에 한개만 골라서 삭제할 때 어렵다.*/ => 레코드(테이블에 들어 있는 값)를 구분하기 위한 조건 1) 해당 컬럼의 값이 중복되어서는 안된다. 2) null 허용해서는 안된다 => null을 허용하면 구분할 수가 없다. 예) 회원 번호를 레코드 구분 컬럼으로 사용한다면 다음과 같이 선언하라! drop table test01; create table test01( tno int unique not null, name char(5) default '홍길동', email char(20) unique ); insert into test01(name,tno) values('홍길동',1); insert into test01(name,tno) values('임꺽정',2); insert into test01(name,email) values('이순신','lee@'); /* tno 는 0이 됨*/ insert into test01(name,email) values('강감찬','kang@'); /* tno 는 0이 됨*/ insert into test01(tno,name,email) values(3,'이순정','lee@'); => 결론 : 1) 값이 중복되어서는 안되는 컬럼은 unique로 선언한다. 2) 레코드를 구분할 때 사용할 컬럼은 unique + not null 로 선언하라! 8. 레코드를 식별하는 컬럼에 대해 unique not null 대신 단축 문법 => primary key -> 어느 컬럼이 식별자로 사용되는지 빠르게 알 수 있다. => unique not null 과 같다. drop table test01; create table test01( tno int primary key, name char(5) default '홍길동', email char(20) unique ); insert into test01(name,email) values('이순신','lee@'); /* tno 는 0이 됨*/ insert into test01(name,email) values('강감찬','kang@'); /* tno 는 0이 됨*/ insert into test01(tno,name,email) values(3,'이순정','leem@');
true
d647580ce9959969d97629f3a9c40f3cfe8b4243
SQL
NohDongWan/Board
/WebContent/sql/member.sql
UHC
280
2.609375
3
[]
no_license
--1. --2. admin, 1234 ϴ. --3. 3 ϴ. create table member( id varchar2(15), password varchar2(10), name varchar2(15), age Number, gender varchar2(5), email varchar2(30), primary key(id)) select * from member;
true
cdd95df7749179ce2e87d0809cfc455a41a3e1fe
SQL
JerryDoran/sql-queries
/Code Snippets/SQL/My Code Snippets/Cursors/Cursor4.sql
UTF-8
543
2.984375
3
[]
no_license
--Declare a cursor DECLARE FilmCursor CURSOR SCROLL FOR SELECT FilmID, FilmName, FilmReleaseDate FROM tblFilm OPEN FilmCursor --Do something useful, Need to move to the first record FETCH ABSOLUTE -10 FROM FilmCursor --Starts 10 records from the bottom of the recordset WHILE @@FETCH_STATUS = 0 --When value of zero is returned by the FETCH_STATUS variable it means that the cursor is successfully fetching the next record. FETCH RELATIVE -10 FROM FilmCursor --step backwards from the cursor CLOSE FilmCursor DEALLOCATE FilmCursor
true
0dfcd39003789623dc569447354e258191b11f5f
SQL
michaelcunningham/oracledba
/projects/DBA-6082/snapshot_errors_before.sql
UTF-8
336
2.78125
3
[]
no_license
drop table snapshot_errors_before; create table snapshot_errors_before as select * from SYS.DBA_ERRORS where name in (select object_name from dba_objects where owner like 'TAG') order by type desc / grant select on snapshot_errors_before to public; create or replace public synonym snapshot_errors_before for snapshot_errors_before;
true
063bc15865bed76d31f827fad34f38ce16ee1a64
SQL
spsanderson/bmhmc-sql
/SQL/Finance/ICR_Exhibit_33/ICR_EXH_33_Cases_Chgs_WOUNDCARE_Non_HBO.sql
UTF-8
633
3.671875
4
[]
no_license
select user_pyr1_Cat , COUNT(DISTINCT(pt_no)) as [Cases] , SUM(tot_chg_Amt) as [Charges] FROM smsdss.BMH_PLM_PtAcct_V WHERE hosp_Svc IN('WCC','WCH') AND Adm_Date BETWEEN '01/01/2017' AND '12/31/2017' AND tot_chg_amt > '0' AND Pt_No NOT IN ( SELECT DISTINCT(a.Pt_id) FROM smsmir.mir_actv as a left outer join smsmir.acct as b ON a.pt_id = b.pt_id WHERE a.actv_cd IN ( '02501005','02501013','02501021','02501039','02501047', '02501054','02501062','02501070','02501088','02501096' ) AND b.adm_Date BETWEEN '01/01/2017' AND '12/31/2017' AND b.hosp_svc in ('WCC','WCH') ) GROUP BY User_Pyr1_Cat ORDER BY user_pyr1_cat ;
true
731fb1553749e548d960cc9ad18dd7778cc7b093
SQL
andytsou19/CRUD
/todo.sql
UTF-8
1,096
3.328125
3
[]
no_license
-- https://www.postgresql.org/docs/current/sql-createtable.html -- https://www.postgresql.org/docs/9.1/datatype-numeric.html -- https://www.postgresqltutorial.com/postgresql-serial/ -- https://www.postgresql.org/docs/12/sql-altertable.html DROP TABLE IF EXISTS todo cascade; CREATE TABLE todo ( _id SERIAL PRIMARY KEY , name varchar NOT NULL ); DROP TABLE IF EXISTS task; CREATE TABLE task ( _id SERIAL PRIMARY KEY , name varchar NOT NULL , status boolean NOT NULL , parent bigint NOT NULL ); ALTER TABLE task ADD CONSTRAINT "parent_fk" FOREIGN KEY ("parent") REFERENCES todo("_id"); --uploading a table --psql -d 'postgres://bqqdneki:b9Gdl_cTf8dPgftZNsQJ3nw2SCJKqAX7@kashin.db.elephantsql.com/bqqdneki' -f todo.sql -- ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address); --https://stackoverflow.com/questions/6842393/import-sql-dump-into-postgresql-database -- -h hostname -U username -- 'postgres://bqqdneki:b9Gdl_cTf8dPgftZNsQJ3nw2SCJKqAX7@kashin.db.elephantsql.com/bqqdneki' -- psql -d databasename -f file.sql
true
9690270d143a15e4196d0b22654f4f15f01bec4a
SQL
muntaza/Open_Persediaan
/sql1_persediaan/buku_penerimaan_barang_sql/buku_penerimaan_dinkes.sql
UTF-8
317
2.640625
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
DROP VIEW IF EXISTS view_buku_penerimaan_dinkes; CREATE VIEW view_buku_penerimaan_dinkes AS SELECT * FROM view_buku_penerimaan_kabupaten WHERE 1 = 1 AND id_skpd = 5; GRANT ALL PRIVILEGES ON view_buku_penerimaan_dinkes TO lap_dinkes; REVOKE INSERT, UPDATE, DELETE ON view_buku_penerimaan_dinkes FROM lap_dinkes;
true
3822fd1f80ded3b97de8769dda3cb66e4b249c3b
SQL
EkkiRu/MyPraktic
/SQL2/Запрос22.sql
UTF-8
772
3.734375
4
[]
no_license
SELECT bolshakov_special.* FROM bolshakov_special INNER JOIN bolshakov_course ON bolshakov_course.special_id = bolshakov_special.special_id INNER JOIN bolshakov_graduate ON bolshakov_graduate.course_id = bolshakov_course.course_id INNER JOIN bolshakov_graduate_time ON bolshakov_graduate_time.gradute_id = bolshakov_graduate.graduate_id LEFT JOIN bolshakov_day ON (bolshakov_graduate_time.day_id = bolshakov_day.day_id) LEFT JOIN bolshakov_lesson_num ON (bolshakov_graduate_time.lesson_num_id = bolshakov_lesson_num.lesson_num_id) WHERE bolshakov_lesson_num.time_lesson BETWEEN '14:00:00' and '18:00:00' AND (bolshakov_day.name = 'Четверг' OR bolshakov_day.name = 'Суббота') AND bolshakov_day.day_id IS NULL AND bolshakov_lesson_num.lesson_num_id IS NULL
true
09c4b8b08e8b81a0b3e1a6908245feee7c665c75
SQL
gioado7/freeuni-hub
/src/main/database/usersInfo.sql
UTF-8
341
2.65625
3
[]
no_license
create table usersInfo ( user_id int not null, constraint foreign key (user_id) references users (id) on delete restrict on update cascade, user_name varchar(100), user_last_name varchar(100), sqesi varchar(100), course varchar(100), courseNum int, image longBlob );
true
2ed65c1aa81a7e7f7133a69715b5a7418aaa40c1
SQL
RaizerVarela/EX_POO
/Video/Tabela/prod.sql
UTF-8
819
3.46875
3
[]
no_license
create database prod; use prod; create table categoria( id_cat int(11) not null auto_increment, nome_categoria varchar(30) not null, primary key (id_cat) ); create table produtos( id_prod int(11) not null auto_increment, nome_produto varchar(100) not null, valor double not null, id_cat integer not null, primary key (id_prod), foreign key (id_cat) references categoria (id_cat) ); insert into categoria (nome_categoria) values ('Computadores'), ('Ferramentas'), ('Limpeza'), ('Vestimenta'); insert into produtos (nome_produto, valor, id_cat) values ('notebook acer', 2500, 1), ('notebook asus', 3000, 1), ('notebook lenovo', 2700, 1), ('Conjunto ferramentas', 110, 2), ('Chave de fenda', 12, 2), ('Palha de aço', 1.5, 3), ('Esponja', 1, 3), ('Camiseta', 20, 4), ('Calça', 30, 4);
true
6616d8e83d51998e94bb75b07d0dd4e2c4f582fc
SQL
v3921358/Lidium
/sql/seperate/60-playernpcs.sql
UTF-8
651
2.609375
3
[ "Apache-2.0" ]
permissive
CREATE TABLE IF NOT EXISTS `playernpcs` ( `id` int(11) NOT NULL, `name` varchar(13) NOT NULL, `hair` int(11) NOT NULL, `face` int(11) NOT NULL, `skin` int(11) NOT NULL, `x` int(11) NOT NULL DEFAULT 0, `y` int(11) NOT NULL DEFAULT 0, `map` int(11) NOT NULL, `charid` int(11) NOT NULL, `scriptid` int(11) NOT NULL, `foothold` int(11) NOT NULL, `dir` tinyint(1) NOT NULL DEFAULT 0, `gender` tinyint(1) NOT NULL DEFAULT 0, `pets` varchar(25) DEFAULT '0,0,0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `playernpcs` ADD PRIMARY KEY (`id`), ADD KEY `scriptid` (`scriptid`), ADD KEY `playernpcs_ibfk_1` (`charid`);
true
4fdebfc0ad2ac64718ed76cf8b130a94b356a331
SQL
bellmit/origin
/family_order/sql/.svn/pristine/02/029bf55c2a30dd0a0924eb8bb24746da1a2a0718.svn-base
UTF-8
458
2.765625
3
[]
no_license
--IS_CACHE=Y SELECT product_id,to_char(start_date,'yyyy-mm-dd hh24:mi:ss') start_date,to_char(end_date,'yyyy-mm-dd hh24:mi:ss') end_date,release_eparchy_code,release_staff_id,release_depart_id,to_char(release_time,'yyyy-mm-dd hh24:mi:ss') release_time FROM td_b_product_release WHERE product_id = :PRODUCT_ID AND start_date = TO_DATE(:START_DATE,'YYYY-MM-DD HH24:MI:SS') AND (release_eparchy_code = :RELEASE_EPARCHY_CODE OR release_eparchy_code = 'ZZZZ')
true
a8d342434c96475f1062d6e10b11d72c957b49cd
SQL
batego/db_fintra
/fintra/etes/Tables/etes.manifiesto_carga.sql
UTF-8
5,865
2.515625
3
[]
no_license
-- Table: etes.manifiesto_carga -- DROP TABLE etes.manifiesto_carga; CREATE TABLE etes.manifiesto_carga ( id serial NOT NULL, reg_status character varying(1) NOT NULL DEFAULT ''::character varying, dstrct character varying(4) NOT NULL DEFAULT 'FINV'::character varying, periodo character varying(6) NOT NULL DEFAULT ''::character varying, id_agencia integer NOT NULL, id_vehiculo integer NOT NULL, id_conductor integer NOT NULL, id_intermediario integer NOT NULL, id_proserv integer NOT NULL, planilla character varying(20) NOT NULL DEFAULT ''::character varying, origen character varying(80) NOT NULL DEFAULT ''::character varying, destino character varying(80) NOT NULL DEFAULT ''::character varying, fecha_creacion_anticipo timestamp without time zone NOT NULL, fecha_envio_fintra timestamp without time zone NOT NULL, valor_planilla numeric(11,2) NOT NULL DEFAULT 0, valor_neto_anticipo numeric(11,2) NOT NULL DEFAULT 0, valor_descuentos_fintra numeric(11,2) NOT NULL DEFAULT 0, porc_comision_intermediario numeric NOT NULL DEFAULT 0, valor_comision_intermediario numeric NOT NULL DEFAULT 0, valor_desembolsar numeric NOT NULL DEFAULT 0, fecha_contabilizacion timestamp without time zone NOT NULL DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, periodo_contabilizacion character varying(6) NOT NULL DEFAULT ''::character varying, fecha_anulacion_contabilizacion timestamp without time zone NOT NULL DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, periodo_anulacion_contabilizacion character varying(6) NOT NULL DEFAULT ''::character varying, transaccion integer NOT NULL DEFAULT 0, transaccion_anulacion integer NOT NULL DEFAULT 0, aprobado character varying(1) NOT NULL DEFAULT 'N'::character varying, fecha_aprobacion timestamp without time zone NOT NULL DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, usuario_anulacion character varying(10) NOT NULL DEFAULT ''::character varying, fecha_anulacion timestamp without time zone NOT NULL DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, enviado_eds character varying(1) NOT NULL DEFAULT 'N'::character varying, fecha_envio_eds timestamp without time zone NOT NULL DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, transferido character varying(1) NOT NULL DEFAULT 'N'::character varying, fecha_transferencia timestamp without time zone NOT NULL DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, numero_egreso character varying(20) NOT NULL DEFAULT ''::character varying, valor_egreso numeric(11,2) NOT NULL DEFAULT 0, reanticipo character varying(1) NOT NULL DEFAULT 'N'::character varying, usuario_aprobacion character varying(20) NOT NULL DEFAULT ''::character varying, fecha_pago_fintra timestamp without time zone NOT NULL DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, documento_cxp character varying(50) NOT NULL DEFAULT ''::character varying, fecha_corrida timestamp without time zone DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, cxc_corrida character varying(50) NOT NULL DEFAULT ''::character varying, creation_date timestamp without time zone NOT NULL DEFAULT now(), creation_user character varying(10) NOT NULL DEFAULT ''::character varying, last_update timestamp without time zone NOT NULL DEFAULT '0099-01-01 00:00:00'::timestamp without time zone, user_update character varying(10) NOT NULL DEFAULT ''::character varying, banco character varying(100) NOT NULL DEFAULT ''::character varying, sucursal character varying(100) NOT NULL DEFAULT ''::character varying, cedula_titular_cuenta character varying(100) NOT NULL DEFAULT ''::character varying, nombre_titular_cuenta character varying(200) NOT NULL DEFAULT ''::character varying, tipo_cuenta character varying(50) NOT NULL DEFAULT ''::character varying, no_cuenta character varying(100) NOT NULL DEFAULT ''::character varying, CONSTRAINT fk_manifiestocarga_agencia FOREIGN KEY (id_agencia) REFERENCES etes.agencias (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT fk_manifiestocarga_conductor FOREIGN KEY (id_conductor) REFERENCES etes.conductor (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT fk_manifiestocarga_idproserv FOREIGN KEY (id_proserv) REFERENCES etes.productos_servicios_transp (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT fk_manifiestocarga_intermediario FOREIGN KEY (id_intermediario) REFERENCES etes.intermediario (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT fk_manifiestocarga_vehiculo FOREIGN KEY (id_vehiculo) REFERENCES etes.vehiculo (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT manifiesto_carga_destino_check CHECK (destino::text <> ''::text AND destino::text <> ' '::text AND destino::text <> ' '::text), CONSTRAINT manifiesto_carga_origen_check CHECK (origen::text <> ''::text AND origen::text <> ' '::text AND origen::text <> ' '::text), CONSTRAINT manifiesto_carga_planilla_check CHECK (planilla::text <> ''::text AND planilla::text <> ' '::text AND planilla::text <> ' '::text) ) WITH ( OIDS=FALSE ); ALTER TABLE etes.manifiesto_carga OWNER TO postgres; -- Trigger: anular_cxp_transferencia on etes.manifiesto_carga -- DROP TRIGGER anular_cxp_transferencia ON etes.manifiesto_carga; CREATE TRIGGER anular_cxp_transferencia AFTER UPDATE ON etes.manifiesto_carga FOR EACH ROW EXECUTE PROCEDURE etes.anular_cxp_transferencia(); -- Trigger: crear_cxp_transferencia on etes.manifiesto_carga -- DROP TRIGGER crear_cxp_transferencia ON etes.manifiesto_carga; CREATE TRIGGER crear_cxp_transferencia AFTER UPDATE ON etes.manifiesto_carga FOR EACH ROW EXECUTE PROCEDURE etes.crear_cxp_transferencia();
true
8933bbc5cff26064d0bdbb51664a8be183bd5d47
SQL
Jekkill/photographer
/photographer.sql
UTF-8
11,063
2.6875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Хост: 127.0.0.1 -- Время создания: Янв 28 2018 г., 07:31 -- Версия сервера: 10.1.29-MariaDB -- Версия PHP: 7.2.0 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 */; -- -- База данных: `photographer` -- -- -------------------------------------------------------- -- -- Структура таблицы `connection` -- CREATE TABLE `connection` ( `connection_id` int(10) UNSIGNED NOT NULL, `connection_user_id` int(10) UNSIGNED NOT NULL, `connection_session_id` varchar(100) NOT NULL, `connection_token` char(32) NOT NULL, `connection_expire` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `connection` -- INSERT INTO `connection` (`connection_id`, `connection_user_id`, `connection_session_id`, `connection_token`, `connection_expire`) VALUES (27, 14, 'r4930gl85ls9kiet94l9hmtr6b', 'byv0diil5nf6cg2punuvs7ff6ukbrupo', '2018-01-23 18:30:42'), (28, 14, 'qgfgujv8m6nti80opm0i2mcdjh', '34q9f7ilh5kftr4j09qks3vh3fc3kkzk', '2018-01-26 11:42:45'), (29, 14, 'qgfgujv8m6nti80opm0i2mcdjh', '34q9f7ilh5kftr4j09qks3vh3fc3kkzk', '2018-01-26 11:42:45'), (30, 14, 'qgfgujv8m6nti80opm0i2mcdjh', '34q9f7ilh5kftr4j09qks3vh3fc3kkzk', '2018-01-26 11:42:45'), (31, 14, 'abjhb23ku62sptb9ql9fnpag3l', 'j5wznhhijos2url6kbgrv4adxu8z7e0k', '2018-01-27 22:16:38'), (32, 14, 'i5871s9j8g1bd0vmc61nd1bc5t', 'rmj3aign29hxrloulefqp8s30ifaitqa', '2018-01-27 09:45:44'), (33, 14, '8g19ar7lipvcr67icdvmghao5b', 'wvdf6zt4c2thnmqik6zwmiv74tpq57uq', '2018-01-27 09:55:31'), (34, 14, 'i99budj5kbneqs698japs98rfl', 'wkj4w3yesori2x7lhtmy46uf4fiwe6g8', '2018-01-27 09:56:05'), (35, 14, 'jghqlq9r2h8plc9mnmrssdnmbr', 'qua7pvxx0b8mwrbtt10wospwa8094hbs', '2018-01-27 10:16:59'), (36, 14, 'abjhb23ku62sptb9ql9fnpag3l', 'j5wznhhijos2url6kbgrv4adxu8z7e0k', '2018-01-27 22:16:38'), (37, 14, '0q1v2q1vl99e41eg4l744nkjiu', 'puk2scgvr4parv353tmtlmesns6vxfs2', '2018-01-27 23:09:40'); -- -------------------------------------------------------- -- -- Структура таблицы `feedback` -- CREATE TABLE `feedback` ( `feedback_id` int(10) UNSIGNED NOT NULL, `feedback_user_id` int(10) UNSIGNED NOT NULL, `feedback_text` varchar(500) NOT NULL, `feedback_path_to_image` varchar(500) NOT NULL, `feedback_date` date NOT NULL, `feedback_is_checked` tinyint(4) UNSIGNED NOT NULL, `feedback_is_visible` tinyint(4) UNSIGNED NOT NULL, `feedback_is_deleted` tinyint(4) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `feedback` -- INSERT INTO `feedback` (`feedback_id`, `feedback_user_id`, `feedback_text`, `feedback_path_to_image`, `feedback_date`, `feedback_is_checked`, `feedback_is_visible`, `feedback_is_deleted`) VALUES (1, 1, ' Знаю Веру очень давно, около 5 лет. Каждый раз при необходимости прихожу к ней фотографироваться - никогда никаких проблем не было, фотографии она всегда делает быстро и отдает их заблаговременно. К тому же, в отличии от других фотографов, ведет себя сдержано и , естественно, никогда не позволяет себе повысить голос. ', 'sfasffsfdhsdvafdsfasf897.jpg', '2016-11-10', 1, 1, 0), (2, 2, 'Отмечаю пунктуальность и профессионализм (снимки делались с огромной скоростью, видно, что выбор тех или иных настроек камеры выполнялся за доли секунды). Прекрасное чувство юмора, благодаря которому хорошие снимки получились даже в конце дня, когда все падали с ног. ', 'dfakjfhasjfhasgfafkl8789.jpg', '2017-02-20', 1, 1, 0), (3, 3, 'Спасибо огромное, Вера, за потрясающие фотографии! Вы заряжали нас энергией весь день, с вами было легко и приятно работать. Я боялась, что очень устану на прогулке, но она пронеслась как одно мгновение.', 'sfgasfahassfas7878.jpg', '2017-05-15', 1, 1, 0), (4, 5, 'Очень рады, что, выбирая фотографа на свадьбу, в итоге обратились к Вере. На протяжении всей подготовки к событию она отвечала на возникающие вопросы по фотосессии и не только, в день свадьбы приехала вовремя, на протяжении всего дня работала очень деликатно и ненавязчиво.', 'dsadavaxfjahfjhasf7878.jpg', '2017-10-16', 1, 1, 0), (6, 12, 'asfadgadsgzxczsdasf', 'noPhoto.jpg', '2018-01-21', 0, 0, 1), (7, 15, ' ufkajslkjflk;dsa ', 'noPhoto.jpg', '2018-01-22', 0, 0, 1), (12, 23, ' Спасибо большое Вере за фото нашего камерного праздника! Фотографии получились очень живыми, естественным, потому что мы были собой, а Вера это все \"словила\" и оформила в карточки, которые всю жизнь будут напоминать нам об этом событии и греть сердце. ', '1517083368.jpg', '2018-01-27', 1, 1, 0); -- -------------------------------------------------------- -- -- Структура таблицы `request` -- CREATE TABLE `request` ( `request_id` int(10) UNSIGNED NOT NULL, `request_user_id` int(10) UNSIGNED NOT NULL, `request_date` date DEFAULT NULL, `request_text` varchar(500) DEFAULT NULL, `request_is_checked` tinyint(4) UNSIGNED NOT NULL, `request_is_deleted` tinyint(4) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `request` -- INSERT INTO `request` (`request_id`, `request_user_id`, `request_date`, `request_text`, `request_is_checked`, `request_is_deleted`) VALUES (1, 1, '2018-02-02', ' Нужен фотограф на детский праздник. Сможете ?', 1, 0), (2, 5, '2018-02-25', ' В этот день нужно будет пофотографировать детей на празднике. Поможете? ', 1, 0), (3, 16, '2018-01-31', 'HSfhashfhaslfhahsfh', 0, 1), (4, 18, '2018-03-09', ' В этот день хотим сыграть свадьбу с девушкой. Хотелось бы проконсультироваться насчёт цены. ', 1, 0), (5, 22, '2018-03-08', 'Необходима съёмка корпоратива 8 марта. Сможете?', 1, 0); -- -------------------------------------------------------- -- -- Структура таблицы `user` -- CREATE TABLE `user` ( `user_id` int(10) UNSIGNED NOT NULL, `user_name` varchar(50) NOT NULL, `user_email` varchar(100) NOT NULL, `user_number` varchar(50) DEFAULT NULL, `user_is_deleted` tinyint(4) UNSIGNED NOT NULL, `user_is_admin` tinyint(4) UNSIGNED NOT NULL, `user_password` char(32) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `user` -- INSERT INTO `user` (`user_id`, `user_name`, `user_email`, `user_number`, `user_is_deleted`, `user_is_admin`, `user_password`) VALUES (1, 'Юлия', 'uliya@rambler.ru', '79217455465', 0, 0, NULL), (2, 'Василий', 'vasilii@yandex.ru', NULL, 0, 0, NULL), (3, 'Антонина', 'tonya@gmail.com', '79513428590', 0, 0, NULL), (4, 'Василиса', 'vasilisa@gmail.ru', NULL, 0, 0, NULL), (5, 'Дмитрий', 'dmitrii@mail.ru', '79505552136', 0, 0, NULL), (12, 'Elena', 'jakdsjfkajsfk@fjaskjadkg.ashf', NULL, 0, 0, NULL), (14, '', 'admin@admin.ru', NULL, 0, 1, 'a5e70b2d3967e62733bf294d239792c4'), (15, 'egdsgqw', 'sdgsd@agsad.ru', NULL, 0, 0, NULL), (16, 'HJdfajf', 'asjfjaksfj@asfjask.ru', '78413241686', 0, 0, NULL), (18, 'Андрей', 'andrei@gmail.com', '79536574532', 0, 0, NULL), (21, 'djkfjlksjds\';v', 'asfasfas@favzxvs.ru', NULL, 0, 0, NULL), (22, 'Александр', 'alexandr@gmail.com', '79213456789', 0, 0, NULL), (23, 'Арина', 'arina@gmail.com', NULL, 0, 0, NULL); -- -- Индексы сохранённых таблиц -- -- -- Индексы таблицы `connection` -- ALTER TABLE `connection` ADD PRIMARY KEY (`connection_id`), ADD KEY `connection_user_id` (`connection_user_id`); -- -- Индексы таблицы `feedback` -- ALTER TABLE `feedback` ADD PRIMARY KEY (`feedback_id`), ADD KEY `feedback_user_id` (`feedback_user_id`); -- -- Индексы таблицы `request` -- ALTER TABLE `request` ADD PRIMARY KEY (`request_id`), ADD KEY `request_user_id` (`request_user_id`); -- -- Индексы таблицы `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `user_email` (`user_email`); -- -- AUTO_INCREMENT для сохранённых таблиц -- -- -- AUTO_INCREMENT для таблицы `connection` -- ALTER TABLE `connection` MODIFY `connection_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38; -- -- AUTO_INCREMENT для таблицы `feedback` -- ALTER TABLE `feedback` MODIFY `feedback_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT для таблицы `request` -- ALTER TABLE `request` MODIFY `request_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT для таблицы `user` -- ALTER TABLE `user` MODIFY `user_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24; -- -- Ограничения внешнего ключа сохраненных таблиц -- -- -- Ограничения внешнего ключа таблицы `connection` -- ALTER TABLE `connection` ADD CONSTRAINT `connection_ibfk_1` FOREIGN KEY (`connection_user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ограничения внешнего ключа таблицы `feedback` -- ALTER TABLE `feedback` ADD CONSTRAINT `feedback_ibfk_1` FOREIGN KEY (`feedback_user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ограничения внешнего ключа таблицы `request` -- ALTER TABLE `request` ADD CONSTRAINT `request_ibfk_1` FOREIGN KEY (`request_user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE; 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
75ac08d676b1b5ced6c39df4d16912aeaf0088a4
SQL
narminsn/Flask_ajax
/data.sql
UTF-8
261
2.703125
3
[]
no_license
-- CREATE TABLE users_sign ( -- id SERIAL PRIMARY KEY, -- full_name VARCHAR(255) NOT NULL, -- email VARCHAR(200) UNIQUE NOT NULL, -- password TEXT NOT NULL, -- sign_date TIMESTAMP DEFAULT NOW() -- ); -- DELETE FROM users_sign WHERE id=3;
true
0ed74b3174e0f0cd31ec2af1229da41aada2914d
SQL
dimuls/face-recognizer
/alerter/db/schema.sql
UTF-8
195
2.640625
3
[]
no_license
create table person ( id bigserial primary key, name text not null ); create table face ( person_id bigint not null references person(id), descriptor real[128] not null unique );
true
5614c2adaeee995ada4ad1076fac81cd3c5d8a87
SQL
ilya5006/kursovaya-1
/kursovanya-1.sql
UTF-8
11,338
3.171875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Хост: 127.0.0.1:3306 -- Время создания: Май 26 2019 г., 21:30 -- Версия сервера: 8.0.12 -- Версия PHP: 7.2.10 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 */; -- -- База данных: `kursovanya-1` -- -- -------------------------------------------------------- -- -- Структура таблицы `cloth` -- CREATE TABLE `cloth` ( `article` varchar(25) NOT NULL, `name` varchar(25) NOT NULL, `color` varchar(25) NOT NULL, `picture` text NOT NULL, `image` text NOT NULL, `composition` varchar(30) NOT NULL, `width` int(11) NOT NULL, `length` int(11) NOT NULL, `price` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `cloth` -- INSERT INTO `cloth` (`article`, `name`, `color`, `picture`, `image`, `composition`, `width`, `length`, `price`) VALUES ('tkan_1', 'Хорошая ткань', 'Чёрный', 'URL', 'https://www.decor-doma.ru/wa-data/public/shop/products/58/40/14058/images/11470/11470.970.jpg', 'Водородные смеси', 123, 321, 10000000), ('tkan_2', 'Ещё одна ткань', 'Красный', 'URL', 'https://moychay.ru/system/product_fotos/images/000/400/132/original/_MG_1078_%D0%BA%D0%BE%D0%BF%D0%B8%D1%8F.jpg?1492860734', 'Хорошо', 424, 1234, 435); -- -------------------------------------------------------- -- -- Структура таблицы `cloth_product` -- CREATE TABLE `cloth_product` ( `article_cloth` varchar(25) NOT NULL, `article_product` varchar(25) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `cloth_product` -- INSERT INTO `cloth_product` (`article_cloth`, `article_product`) VALUES ('tkan_1', '1'), ('tkan_2', '1'); -- -------------------------------------------------------- -- -- Структура таблицы `furniture` -- CREATE TABLE `furniture` ( `article` varchar(25) NOT NULL, `name` varchar(30) NOT NULL, `type` varchar(25) NOT NULL, `width` int(11) NOT NULL, `length` int(11) NOT NULL, `weight` int(11) NOT NULL, `image` text NOT NULL, `price` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `furniture` -- INSERT INTO `furniture` (`article`, `name`, `type`, `width`, `length`, `weight`, `image`, `price`) VALUES ('4', 'Шуруп', 'ШурупЫ', 1234, 413, 124123, 'https://st0.isolux.ru/media/catalog/product/cache/1/image/602f0fa2c1f0d1ba5e241f914e856ff9/_/x/_xtn_1_1.jpg?kar=1&kf=1&kt=1&co=1&rgb%5B0%5D=255&rgb%5B1%5D=255&rgb%5B2%5D=255&ang=ang&qua=90', 14213); -- -------------------------------------------------------- -- -- Структура таблицы `furniture_product` -- CREATE TABLE `furniture_product` ( `article_furniture` varchar(25) NOT NULL, `article_product` varchar(25) NOT NULL, `placement` varchar(25) NOT NULL, `width` int(11) DEFAULT NULL, `length` int(11) DEFAULT NULL, `rotate` int(11) DEFAULT NULL, `count` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `furniture_product` -- INSERT INTO `furniture_product` (`article_furniture`, `article_product`, `placement`, `width`, `length`, `rotate`, `count`) VALUES ('4', '1', 'ул. Строителей, д.Саша', 424, 23213, 24, 12521); -- -------------------------------------------------------- -- -- Структура таблицы `orders` -- CREATE TABLE `orders` ( `number` int(11) NOT NULL, `date` date NOT NULL, `stage` varchar(25) NOT NULL, `customer` varchar(25) NOT NULL, `manager` varchar(25) DEFAULT NULL, `price` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `orders` -- INSERT INTO `orders` (`number`, `date`, `stage`, `customer`, `manager`, `price`) VALUES (4242, '2019-05-09', 'Подготавливается', 'zakazchik', 'manager', 15151); -- -------------------------------------------------------- -- -- Структура таблицы `orders_product` -- CREATE TABLE `orders_product` ( `article` varchar(25) NOT NULL, `number_order` int(11) NOT NULL, `counts_product` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `orders_product` -- INSERT INTO `orders_product` (`article`, `number_order`, `counts_product`) VALUES ('1', 4242, 5); -- -------------------------------------------------------- -- -- Структура таблицы `products` -- CREATE TABLE `products` ( `article` varchar(25) NOT NULL, `name` varchar(25) NOT NULL, `width` int(11) NOT NULL, `length` int(11) NOT NULL, `image` text, `comment` text ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT; -- -- Дамп данных таблицы `products` -- INSERT INTO `products` (`article`, `name`, `width`, `length`, `image`, `comment`) VALUES ('1', 'Диван', 424, 52154, 'https://cdn.mebelvia.ru/upload/resize_cache/iblock/9eb/750_563_1/divan_vernon_1.jpg?1516957203140118', 'Хороший диван, очень большой, прям очень\r\nЯ бы сказал, что это лучший диван, который существует на этом свете.'); -- -------------------------------------------------------- -- -- Структура таблицы `storage_cloth` -- CREATE TABLE `storage_cloth` ( `roll` int(11) NOT NULL, `article_cloth` varchar(25) NOT NULL, `width` int(11) NOT NULL, `length` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `storage_cloth` -- INSERT INTO `storage_cloth` (`roll`, `article_cloth`, `width`, `length`) VALUES (1, 'tkan_1', 44, 22), (3, 'tkan_2', 4324, 6353); -- -------------------------------------------------------- -- -- Структура таблицы `storage_furniture` -- CREATE TABLE `storage_furniture` ( `party` int(11) NOT NULL, `article_furniture` varchar(25) NOT NULL, `count` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `storage_furniture` -- INSERT INTO `storage_furniture` (`party`, `article_furniture`, `count`) VALUES (1, '4', 50); -- -------------------------------------------------------- -- -- Структура таблицы `user` -- CREATE TABLE `user` ( `login` varchar(25) NOT NULL, `password` varchar(25) NOT NULL, `role` varchar(25) NOT NULL, `name` varchar(25) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `user` -- INSERT INTO `user` (`login`, `password`, `role`, `name`) VALUES ('director', '123', 'Директор', 'Директор'), ('kladman', '123', 'Кладовщик', 'кладмен'), ('manager', '123', 'Менеджер', 'Манагер'), ('zakazchik', '123', 'Заказчик', 'заказчек'); -- -- Индексы сохранённых таблиц -- -- -- Индексы таблицы `cloth` -- ALTER TABLE `cloth` ADD PRIMARY KEY (`article`); -- -- Индексы таблицы `cloth_product` -- ALTER TABLE `cloth_product` ADD PRIMARY KEY (`article_cloth`,`article_product`), ADD KEY `article_cloth` (`article_cloth`), ADD KEY `article_product` (`article_product`); -- -- Индексы таблицы `furniture` -- ALTER TABLE `furniture` ADD PRIMARY KEY (`article`); -- -- Индексы таблицы `furniture_product` -- ALTER TABLE `furniture_product` ADD PRIMARY KEY (`article_furniture`,`article_product`), ADD KEY `article_furniture` (`article_furniture`), ADD KEY `article_product` (`article_product`); -- -- Индексы таблицы `orders` -- ALTER TABLE `orders` ADD PRIMARY KEY (`number`,`date`), ADD KEY `manager` (`manager`), ADD KEY `customer` (`customer`); -- -- Индексы таблицы `orders_product` -- ALTER TABLE `orders_product` ADD PRIMARY KEY (`article`,`number_order`), ADD KEY `article` (`article`), ADD KEY `number_order` (`number_order`); -- -- Индексы таблицы `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`article`); -- -- Индексы таблицы `storage_cloth` -- ALTER TABLE `storage_cloth` ADD PRIMARY KEY (`roll`,`article_cloth`), ADD KEY `article_cloth` (`article_cloth`); -- -- Индексы таблицы `storage_furniture` -- ALTER TABLE `storage_furniture` ADD PRIMARY KEY (`party`,`article_furniture`), ADD KEY `article_furniture` (`article_furniture`); -- -- Индексы таблицы `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`login`,`password`); -- -- Ограничения внешнего ключа сохраненных таблиц -- -- -- Ограничения внешнего ключа таблицы `cloth_product` -- ALTER TABLE `cloth_product` ADD CONSTRAINT `cloth_product_ibfk_1` FOREIGN KEY (`article_cloth`) REFERENCES `cloth` (`article`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `cloth_product_ibfk_2` FOREIGN KEY (`article_product`) REFERENCES `products` (`article`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ограничения внешнего ключа таблицы `furniture_product` -- ALTER TABLE `furniture_product` ADD CONSTRAINT `furniture_product_ibfk_1` FOREIGN KEY (`article_furniture`) REFERENCES `furniture` (`article`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `furniture_product_ibfk_2` FOREIGN KEY (`article_product`) REFERENCES `products` (`article`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ограничения внешнего ключа таблицы `orders` -- ALTER TABLE `orders` ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer`) REFERENCES `user` (`login`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`manager`) REFERENCES `user` (`login`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ограничения внешнего ключа таблицы `orders_product` -- ALTER TABLE `orders_product` ADD CONSTRAINT `orders_product_ibfk_1` FOREIGN KEY (`number_order`) REFERENCES `orders` (`number`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `orders_product_ibfk_2` FOREIGN KEY (`article`) REFERENCES `products` (`article`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ограничения внешнего ключа таблицы `storage_cloth` -- ALTER TABLE `storage_cloth` ADD CONSTRAINT `storage_cloth_ibfk_1` FOREIGN KEY (`article_cloth`) REFERENCES `cloth` (`article`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ограничения внешнего ключа таблицы `storage_furniture` -- ALTER TABLE `storage_furniture` ADD CONSTRAINT `storage_furniture_ibfk_1` FOREIGN KEY (`article_furniture`) REFERENCES `furniture` (`article`) ON DELETE CASCADE ON UPDATE CASCADE; 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
f0386fde98426ceec47c217fff7fd2bf84c020a8
SQL
perapong/mpol-showdocument
/SQL/BSmart/FindBonusReward_9A9D.sql
UTF-8
1,838
3.359375
3
[]
no_license
1. Summary Award CREATE TABLE ZMAI01_9A9B_262012 AS SELECT optpoint_campaign campaign, optpoint_prog_ref prog_ref, optpnt_type, px.optupd_rep_code rep_code, px.optrefer_trans_year trans_year, px.optrefer_trans_group trans_group, px.optrefer_trans_no tran_no, sum(optgross_sales) optgross_sales , SUM(optnet_sales) optnet_sales FROM om_transaction_pnt PX where optou_code ='000' and optpoint_campaign ='262012' and optrefer_trans_group ='11' and optpoint_prog_ref IN ('9A','9B','9C','9D') and optpnt_type iN ('A','V') and optpnt_type !='C' Group by optpoint_campaign ,optpoint_prog_ref ,optpnt_type,px.optupd_rep_code ,px.optrefer_trans_year ,px.optrefer_trans_group ,px.optrefer_trans_no ; ------- 2. : Export data to Excel & Check data SELECT campaign, rep_code, prog_ref, optpnt_type, sum(netmis) netmis, sum(netfri)netfri FROM ZMAI01_9A9B_262012 where campaign ='262012' group by campaign, prog_ref,optpnt_type,rep_code 3. Manual Check data Import data to : BW_AWARD9A_REP 4. Execute Script Insert into bw_award9a_rep (rep_code, campaign, prog_ref, optpnt_type, trans_year, trans_group, invoice_no,prn_rep, gross_amt,net_amt) SELECT rep_code, campaign, prog_ref, optpnt_type, trans_year, trans_group, tran_no invoice_no, 'REP' prn_rep , sum(optgross_sales) gross_amt , sum(optnet_sales) net_amt FROM zmai01_9a9b_262012 zx where exists (select rep_code FROM bw_award9a_rep tx where tx.rep_code = zx.rep_code) group by campaign, prog_ref, optpnt_type, rep_code, trans_year, trans_group, tran_no; 5. Print report : BEBWRP07 Menu : >>Better way program >> Report >>> Bonus gold reward 26 (C7-C10)
true
f8103596aee3a59c3b5396f9aaa79226fb908171
SQL
silberov/inu-backend
/prisma/migrations/20210116070159_make_reset_token_unique/migration.sql
UTF-8
307
2.546875
3
[]
no_license
/* Warnings: - The migration will add a unique constraint covering the columns `[reset_token]` on the table `Password_reset`. If there are existing duplicate values, the migration will fail. */ -- CreateIndex CREATE UNIQUE INDEX `Password_reset.reset_token_unique` ON `Password_reset`(`reset_token`);
true
ffd8544827be9171e3b1a2e69d3d687c099fd8fa
SQL
kellyeryan/phrg-sql-crowdfunding-lab-pca-000
/lib/insert.sql
UTF-8
5,031
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
INSERT INTO users (id, name, age) VALUES (1, "Alonzo", 12); INSERT INTO users (id, name, age) VALUES (2, "Baron", 34); INSERT INTO users (id, name, age) VALUES (3, "Cassidy", 22); INSERT INTO users (id, name, age) VALUES (4, "Derek", 34); INSERT INTO users (id, name, age) VALUES (5, "Ernest", 44); INSERT INTO users (id, name, age) VALUES (6, "Fred", 42); INSERT INTO users (id, name, age) VALUES (7, "Gail", 60); INSERT INTO users (id, name, age) VALUES (8, "Hannah", 71); INSERT INTO users (id, name, age) VALUES (9, "Irma", 23); INSERT INTO users (id, name, age) VALUES (10, "Jack", 24); INSERT INTO users (id, name, age) VALUES (11, "Kiki", 65); INSERT INTO users (id, name, age) VALUES (12, "Larry", 90); INSERT INTO users (id, name, age) VALUES (13, "Mac", 78); INSERT INTO users (id, name, age) VALUES (14, "Nerd", 20); INSERT INTO users (id, name, age) VALUES (15, "Ola", 50); INSERT INTO users (id, name, age) VALUES (16, "Petrov", 32); INSERT INTO users (id, name, age) VALUES (17, "Quentin", 40); INSERT INTO users (id, name, age) VALUES (18, "Ralph", 89); INSERT INTO users (id, name, age) VALUES (19, "Sandra", 50); INSERT INTO users (id, name, age) VALUES (20, "Tammy", 9); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (1, "Alpaca Research", "animal welfare", 1000, 1999, 2000); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (2, "Bromance Support", "mental health", 2000, 2000, 2001); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (3, "Casual Jeans", "clothing for the needy", 3000, 2001, 2002); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (4, "Delta Force", "military veterans", 4000, 2002, 2003); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (5, "Economic Renewal", "support for needy", 5000, 2004, 2005); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (6, "Family Planning", "pregnancy prevention", 6000, 2005, 2006); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (7, "Group Therapy", "mental health", 7000, 2006, 2007); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (8, "Heart Attacks", "prevention of disease", 8000, 2007, 2008); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (9, "Infant Formula", "help for hungry children", 9000, 2009, 2010); INSERT INTO projects (id, title, category, funding_goal, start_date, end_date) VALUES (10, "Jurassic Park", "genetic research into dinosaurs", 10000, 2011, 2012); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (1, 10, 1, 1); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (2, 20, 1, 2); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (3, 30, 2, 1); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (4, 40, 3, 1); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (5, 50, 3, 4); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (6, 60, 4, 5); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (7, 70, 5, 6); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (8, 80, 6, 7); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (9, 90, 7, 8); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (10, 100, 8, 9); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (11, 110, 9, 10); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (12, 120, 10, 9); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (13, 130, 9, 8); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (14, 140, 8, 7); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (15, 150, 7, 6); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (16, 160, 20, 5); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (17, 170, 19, 4); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (18, 180, 18, 3); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (19, 190, 17, 2); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (20, 200, 16, 1); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (21, 210, 15, 10); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (22, 220, 14, 9); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (23, 230, 13, 8); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (24, 240, 12, 7); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (25, 250, 11, 6); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (26, 260, 10, 1); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (27, 270, 11, 5); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (28, 280, 15, 7); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (29, 290, 20, 3); INSERT INTO pledges (id, amount, user_id, project_id) VALUES (30, 300, 19, 6);
true
f6986f98ca0bc42d42530ae261b605b3e7b2517d
SQL
itolisto/conversa-old
/install/Store Procedures/FT_IS_LOCATION_ACTIVE.sql
UTF-8
665
3.4375
3
[ "MIT" ]
permissive
DROP FUNCTION IF EXISTS `FT_IS_LOCATION_ACTIVE`; DELIMITER $$ CREATE DEFINER=`root`@`localhost` FUNCTION `FT_IS_LOCATION_ACTIVE`(`i_business_id` INT UNSIGNED, `i_location_id` INT UNSIGNED) RETURNS TINYINT UNSIGNED NOT DETERMINISTIC READS SQL DATA SQL SECURITY DEFINER BEGIN DECLARE o_result TINYINT; SELECT `bpt_id` INTO o_result FROM `co_business_push_tokens` WHERE `bpt_business_id` = i_business_id AND `bpt_location` = i_location_id LIMIT 1; IF (o_result IS NULL) THEN # No se encontro alguna ubicacion registrada para este negocio SET o_result = 0; ELSE SET o_result = 1; END IF; RETURN o_result; END$$ DELIMITER ;
true
70dc146d6cf12c3d6c3f202a063894650ad338ee
SQL
Team-Quelccaya/qa-service
/postgresSchema.sql
UTF-8
1,050
3.828125
4
[]
no_license
CREATE TABLE questions ( q_id BIGSERIAL, p_id INTEGER, q_body VARCHAR(200), q_date VARCHAR(50), q_asker_name VARCHAR(100), q_asker_email VARCHAR(100), q_reported INTEGER, q_helpfulness INTEGER ); ALTER TABLE questions ADD CONSTRAINT questions_pkey PRIMARY KEY (q_id); CREATE TABLE answers ( a_id BIGSERIAL, q_id INTEGER, a_body VARCHAR(1000), a_date VARCHAR(200), a_ans_name VARCHAR(100), a_ans_email VARCHAR(150), a_reported INTEGER, a_helpfulness INTEGER ); ALTER TABLE answers ADD CONSTRAINT answers_pkey PRIMARY KEY (a_id); CREATE TABLE photos ( photo_id BIGSERIAL, a_id INTEGER, url VARCHAR(300) ); ALTER TABLE photos ADD CONSTRAINT photos_pkey PRIMARY KEY (photo_id); ALTER TABLE answers ADD CONSTRAINT answers_q_id_fkey FOREIGN KEY (q_id) REFERENCES questions(q_id); ALTER TABLE photos ADD CONSTRAINT photos_a_id_fkey FOREIGN KEY (a_id) REFERENCES answers(a_id); CREATE INDEX idx_product_question ON questions(p_id); CREATE INDEX idx_question_answer ON answers(q_id); CREATE INDEX idx_answer_photo ON photos(a_id);
true
13d892af895f2a03bc32e9a7e800b17fc3f4e5c9
SQL
biesmhp/GOROVI
/bd/GOROVI.sql
UTF-8
4,446
3.03125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Servidor: localhost -- Tiempo de generación: 10-12-2020 a las 19:40:59 -- Versión del servidor: 10.4.14-MariaDB -- Versión de PHP: 7.4.10 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 */; -- -- Base de datos: `GOROVI` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Categorias` -- CREATE TABLE `Categorias` ( `id` int(11) NOT NULL, `nombre` varchar(32) NOT NULL, `imagen` varchar(16) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `Categorias` -- INSERT INTO `Categorias` (`id`, `nombre`, `imagen`) VALUES (5, 'Sombreros', 'imagen.png'), (8, 'Pantalones', 'imagen.png'), (11, 'Zapatos', 'imagen.png'), (12, 'Camisetas', 'imagen.png'), (13, 'Bañadores', 'imagen.png'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Productos` -- CREATE TABLE `Productos` ( `id` int(11) NOT NULL, `nombre` varchar(32) NOT NULL, `descripcion` varchar(64) DEFAULT NULL, `categoria` int(11) NOT NULL, `imagen` varchar(16) NOT NULL, `precio` double NOT NULL, `stock` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `Productos` -- INSERT INTO `Productos` (`id`, `nombre`, `descripcion`, `categoria`, `imagen`, `precio`, `stock`) VALUES (3, 'Flanders', 'Sin descripción. ', 5, 'imagen.png', 2, 0), (4, 'Toporejas', 'Sin descripción. ', 5, 'imagen.png', 4, 0), (5, 'Tophat', 'Sin descripción. ', 5, 'imagen.png', 2, 0), (6, 'Silvercrab', 'Sin descripción. ', 8, 'imagen.png', 16, 0), (7, 'Flamencos', 'Sin descripción. ', 8, 'imagen.png', 8, 0), (8, 'Gigantix', 'Sin descripción. ', 11, 'imagen.png', 10, 0), (9, 'Alpino', 'Sin descripción. ', 12, 'imagen.png', 4, 0), (10, 'Invernalia', 'Sin descripción. ', 12, 'imagen.png', 9, 0); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Usuarios` -- CREATE TABLE `Usuarios` ( `id` int(11) NOT NULL, `usuario` varchar(16) NOT NULL, `contraseña` varchar(32) NOT NULL, `nombre` varchar(32) NOT NULL, `apellidos` varchar(32) NOT NULL, `email` varchar(32) NOT NULL, `imagen` varchar(16) NOT NULL, `rol` varchar(16) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `Usuarios` -- INSERT INTO `Usuarios` (`id`, `usuario`, `contraseña`, `nombre`, `apellidos`, `email`, `imagen`, `rol`) VALUES (31, 'Javi', '4d186321c1a7f0f354b297e8914ab240', 'Javierchu', 'Perez Gutierrez', 'javipg@gmail.com', 'imagen.png', 'administrador'), (41, 'prueba', '81dc9bdb52d04dc20036dbd8313ed055', 'Proban', 'Martinez', 'pmar@correo.com', 'imagen.png', 'cliente'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `Categorias` -- ALTER TABLE `Categorias` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `nombre` (`nombre`); -- -- Indices de la tabla `Productos` -- ALTER TABLE `Productos` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `nombre` (`nombre`,`categoria`) USING BTREE, ADD KEY `categoria_productos` (`categoria`); -- -- Indices de la tabla `Usuarios` -- ALTER TABLE `Usuarios` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `usuario` (`usuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `Categorias` -- ALTER TABLE `Categorias` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT de la tabla `Productos` -- ALTER TABLE `Productos` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT de la tabla `Usuarios` -- ALTER TABLE `Usuarios` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=50; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `Productos` -- ALTER TABLE `Productos` ADD CONSTRAINT `categoria_productos` FOREIGN KEY (`categoria`) REFERENCES `Categorias` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 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
91faca28433c86639fd36ccc107da3b76dcd58d9
SQL
shawnamy/Lifecat-Server
/src/main/resources/sql/Permission.sql
GB18030
752
3.15625
3
[]
no_license
-- auto Generated on 2018-11-28 09:30:40 -- DROP TABLE IF EXISTS `permission`; CREATE TABLE permission( `id` INTEGER(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'id', `permission_id` VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'ȨID', `permission_name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'Ȩ', `permission_desc` VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'Ȩ', `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'createTime', `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'updateTime', `is_deleted` INTEGER(12) NOT NULL DEFAULT -1 COMMENT 'isDeleted', PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT 'permission';
true
93753f1b8d292f73f2b18cbace895c902d907ad4
SQL
sebaspala02/taller1ElectivaII
/resource/db/farmacia (1).sql
UTF-8
27,240
3.453125
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 08-04-2020 a las 18:33:07 -- Versión del servidor: 10.1.28-MariaDB -- Versión de PHP: 7.1.11 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 */; -- ----------------------------------------------------- -- Schema farmacia -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `farmacia` DEFAULT CHARACTER SET utf8 ; USE `farmacia` ; -- -- -- Base de datos: `farmacia` -- DELIMITER $$ -- -- Procedimientos -- CREATE DEFINER=`root`@`localhost` PROCEDURE `buscarCliente` (`vidcliente` INT) BEGIN select nombre,apellido,cedula,genero,fecha_naci from cliente where idcliente=vidcliente; END$$ CREATE PROCEDURE buscarProveedor(vidproveedor int) COMMENT'buscar' BEGIN select id,nit,nombre,ciudad,direccion,telefono from proveedor where id=vidproveedor; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `buscarMedi` (`vidmedicamento` INT) BEGIN select nombre, descrip, fecha_venc, cant, fecha_creado, precio, usuario_idusuario, laboratorio_idlaboratorio from medicamento where idmedicamento=vidmedicamento; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `buscarUsuario` (`vidusuario` INT) BEGIN select cedula,nombre,apellido,correo,tipoUsuario_idTipoUsuario,usuario,password from usuario where idusuario=vidusuario; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `buscarLaboratorio` (`vidlaboratorio` INT) BEGIN select nombre,descrip from laboratorio where idlaboratorio=vidlaboratorio; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `buscarEstante` (`videstante` INT) BEGIN select codigo,categoria,descripcion from estante where idestante=videstante; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `listarCliente` (`vidcliente` INT) BEGIN select idcliente,nombre,apellido,cedula,genero,fecha_naci from cliente order by idcliente; END$$ CREATE PROCEDURE listarProveedor(vidproveedor int) COMMENT'listar' BEGIN select id,nit,nombre,ciudad,direccion,telefono from proveedor order by id; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `listarMedi` (`vidmedicamento` INT) BEGIN select m.idmedicamento,m.nombre, m.descrip as descripcion, m.fecha_venc as vencimiento, m.cant as cantidad, m.fecha_creado as registro, m.precio as precio, u.usuario as usuario, l.nombre as laboratorio, l.idlaboratorio from medicamento m join laboratorio l on m.laboratorio_idlaboratorio = l.idlaboratorio join usuario u on m.usuario_idusuario = u.idusuario order by idmedicamento; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `listarUsuario` (`vidusuario` INT) BEGIN select u.idusuario,u.cedula,u.nombre,u.apellido,u.correo, tp.nombre as tipousuario,u.usuario,u.password from usuario u join tipousuario tp on u.tipoUsuario_idTipoUsuario = tp.idTipoUsuario order by idusuario; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `listarLaboratorio` (`vidlaboratorio` INT) BEGIN select idlaboratorio,nombre,descrip from laboratorio order by idlaboratorio; END$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `listarEstante` (`videstante` INT) BEGIN select idestante,codigo,categoria,descripcion from estante order by idestante; END$$ -- detalleVenta -- LISTAR -- DELIMITER// CREATE PROCEDURE listarDetalleV(viddetalle_venta int) COMMENT'listar' BEGIN select d.iddetalle_venta,d.cant,d.medicamento_idmedicamento,d.venta_idventa,m.nombre from medicamento m join detalle_venta d on m.idmedicamento = d.medicamento_idmedicamento where d.venta_idventa=viddetalle_venta order by iddetalle_venta; END$$ -- call listarDetalleV(2); -- venta -- LISTAR -- DELIMITER// select idventa,fecha_venta,valor_total,cliente_idcliente,usuario_idusuario from venta order by idventa; CREATE PROCEDURE listarVenta(vidventa int) COMMENT'listar' BEGIN select v.idventa,DATE_FORMAT(fecha_venta,'%d/%m/%Y') as fecha_venta, valor_total,c.nombre as cliente, u.usuario as usuario_idusuario from venta v join cliente c on v.cliente_idcliente = c.idcliente join usuario u on v.usuario_idusuario=u.idusuario order by idventa; END$$ -- call listarVenta(0); -- Grafico 1 CREATE PROCEDURE listarGenero(vid INT) BEGIN select c.genero,count(*) as total from cliente c group by genero; END$$ -- call listarGenero(0); -- Grafico 2 CREATE PROCEDURE listarProd(vid INT) BEGIN select m.nombre, sum(cant) as cantidad from medicamento m group by nombre; END$$ -- call listarProd(0); -- Grafico 3 CREATE PROCEDURE listarVentaProd(vid INT) BEGIN select m.nombre,sum(dv.cant) as cantidad, sum(dv.cant * m.precio) as ganancia from medicamento m join detalle_venta dv on dv.medicamento_idmedicamento = m.idmedicamento group by dv.medicamento_idmedicamento order by cantidad desc; END$$ -- call listarVentaProd(0); -- Grafico 4 CREATE PROCEDURE listar4(vid INT) BEGIN select u.nombre,u.apellido,u.cedula,u.usuario,count(*) as ventas, sum(v.valor_total) as ingresos from usuario u join venta v on v.usuario_idusuario = u.idusuario group by v.usuario_idusuario order by ventas desc; END$$ -- call listar4(0); -- Grafico 5 CREATE PROCEDURE listar5(vid INT) BEGIN select v.fecha_venta,count(*) as cantidad,sum(v.valor_total) as ingresos from venta v group by v.fecha_venta; END$$ -- call listar5(0); -- Grafico 5 CREATE PROCEDURE listar6(vid INT) BEGIN SET lc_time_names = 'es_ES'; select DAYNAME(v.fecha_venta) as dia,count(*) as ventas,sum(v.valor_total) as ingresos from venta v group by dia; END$$ -- call listar6(0); -- PL 1 EXCEL CREATE PROCEDURE listarPlUno() BEGIN select c.nombre,c.apellido,c.cedula,count(*) as compras, sum(v.valor_total) as invertido from cliente c join venta v on v.cliente_idcliente = c.idcliente group by v.cliente_idcliente order by compras desc; END$$ -- PL 2 EXCEL = grafico 4 CREATE PROCEDURE listarPlDos() BEGIN select u.nombre,u.apellido,u.cedula,u.usuario,count(*) as ventas, sum(v.valor_total) as ingresos from usuario u join venta v on v.usuario_idusuario = u.idusuario group by v.usuario_idusuario order by ventas desc; END$$ -- PL 3 EXCEL CREATE PROCEDURE listarPlTres() BEGIN select m.nombre,l.nombre as laboratorio,m.descrip as descripcion,sum(dv.cant) as cantidad from medicamento m join detalle_venta dv on dv.medicamento_idmedicamento = m.idmedicamento join laboratorio l on m.laboratorio_idlaboratorio = l.idlaboratorio group by dv.medicamento_idmedicamento order by cantidad desc; END$$ -- PL 4 EXCEL = grafico 5 CREATE PROCEDURE listarPlCuatro() BEGIN select v.fecha_venta,count(*) as cantidad,sum(v.valor_total) as ingresos from venta v group by v.fecha_venta; END$$ -- -- Funciones -- CREATE DEFINER=`root`@`localhost` FUNCTION `editarMedicamento` (`vidmedicamento` INT, `vnombre` VARCHAR(45), `vdescrip` VARCHAR(45), `vfecha_venc` DATE, `vcant` INT, `vfecha_creado` DATE, `vprecio` INT, `vusuario_idusuario` INT, `vlaboratorio_idlaboratorio` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF EXISTS(select idmedicamento from medicamento where idmedicamento=vidmedicamento) THEN update medicamento set nombre=vnombre,descrip=vdescrip,fecha_venc=vfecha_venc,cant=vcant, fecha_creado=vfecha_creado,precio=vprecio,usuario_idusuario=vusuario_idusuario, laboratorio_idlaboratorio=vlaboratorio_idlaboratorio where idmedicamento = vidmedicamento; set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `eliminarCliente` (`vidcliente` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF EXISTS(select idcliente from cliente where idcliente=vidcliente) THEN DELETE FROM cliente WHERE (`idcliente` = `vidcliente`); set res = 1; END IF; RETURN res; END$$ CREATE FUNCTION eliminarProveedor ( `vidproveedor` INT ) RETURNS INT(1) READS SQL DATA DETERMINISTIC BEGIN DECLARE res INT DEFAULT 0; IF EXISTS(select id from proveedor where id=id) THEN DELETE FROM proveedor WHERE (`id` = `vidproveedor`); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `eliminarMedicamento` (`vidmedicamento` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF EXISTS(select idmedicamento from medicamento where idmedicamento=vidmedicamento) THEN delete from medicamento where idmedicamento = vidmedicamento; set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `eliminarUsuario` (`vidusuario` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF EXISTS(select idusuario from usuario where idusuario=vidusuario) THEN DELETE FROM usuario WHERE (`idusuario` = `vidusuario`); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `eliminarLaboratorio` (`vidlaboratorio` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF EXISTS(select idlaboratorio from laboratorio where idlaboratorio=vidlaboratorio) THEN DELETE FROM laboratorio WHERE (`idlaboratorio` = `vidlaboratorio`); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `eliminarEstante` (`videstante` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF EXISTS(select idestante from estante where idestante=videstante) THEN DELETE FROM estante WHERE (`idestante` = `videstante`); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `guardarLaboratorio` (`vnombre` VARCHAR(45), `vdescrip` VARCHAR(45)) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select nombre from laboratorio where nombre=vnombre) THEN insert into laboratorio(nombre,descrip) values(vnombre,vdescrip); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `guardarProveedor` (`vnit` VARCHAR(45),`vnombre` VARCHAR(45),`vciudad` VARCHAR(45),`vdireccion` VARCHAR(45), `vtelefono` VARCHAR(45)) RETURNS INT(1) READS SQL DATA DETERMINISTIC BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select nit from proveedor where nit=vnit) THEN insert into proveedor(nit,nombre,ciudad,direccion,telefono) values(vnit,vnombre,vciudad,vdireccion,vtelefono); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `guardarEstante` (`vcodigo` VARCHAR(45), `vcategoria` VARCHAR(45), `vdescripcion` VARCHAR(45)) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select codigo from estante where codigo=vcodigo) THEN insert into estante(codigo,categoria,descripcion) values(vcodigo,vcategoria,vdescripcion); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `guardarCliente` (`vnombre` VARCHAR(45), `vapellido` VARCHAR(45), `vcedula` INT, `vgenero` VARCHAR(45), `vfecha_naci` DATE) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select cedula from cliente where cedula=vcedula) THEN insert into cliente(nombre,apellido,cedula,genero,fecha_naci) values(vnombre,vapellido,vcedula,vgenero,vfecha_naci); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `guardarMedicamento` (`vnombre` VARCHAR(45), `vdescrip` VARCHAR(45), `vfecha_venc` DATE, `vcant` INT, `vfecha_creado` DATE, `vprecio` INT, `vusuario_idusuario` INT, `vlaboratorio_idlaboratorio` INT, `vproveedor_id` INT, `vestante_idestante` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select idmedicamento from medicamento where nombre=vnombre and laboratorio_idlaboratorio = vlaboratorio_idlaboratorio and proveedor_id = vproveedor_id and estante_idestante = vestante_idestante) THEN insert into medicamento(nombre, descrip, fecha_venc, cant, fecha_creado, precio, usuario_idusuario, laboratorio_idlaboratorio,proveedor_id,estante_idestante) values(vnombre,vdescrip,vfecha_venc,vcant,vfecha_creado,vprecio,vusuario_idusuario,vlaboratorio_idlaboratorio,vproveedor_id,vestante_idestante); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `guardarUsuario` (`vcedula` INT, `vnombre` VARCHAR(45), `vapellido` VARCHAR(45), `vcorreo` VARCHAR(45), `vtipoUsuario` INT, `vusuario` VARCHAR(45), `vpassword` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select cedula from usuario where cedula=vcedula) THEN insert into usuario(cedula,nombre,apellido,correo,tipoUsuario_idTipoUsuario,usuario,password) values(vcedula,vnombre,vapellido,vcorreo,vtipoUsuario,vusuario,vpassword); set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `guardarVenta` (`vtotal` INT(20), `vinv` VARCHAR(2000), `vcant` VARCHAR(2000), `vcliente` INT(20), `vusuario` INT(20)) RETURNS INT(11) NO SQL DETERMINISTIC BEGIN DECLARE res INT DEFAULT 0; DECLARE inv INT DEFAULT -1; DECLARE can INT DEFAULT -1; DECLARE id_ven INT DEFAULT -1; DECLARE inv_old INT DEFAULT 0; DECLARE inv_update INT; insert into venta(valor_total,cliente_idcliente,usuario_idusuario) VALUES (vtotal, vcliente, vusuario); WHILE (LOCATE(',', vinv) > 0) DO SET inv = ELT(1, vinv); SET can = ELT(1, vcant); SET inv_old = (SELECT cant FROM medicamento where idmedicamento = inv); SET inv_update = inv_old - can; SET id_ven = (SELECT MAX(idventa) from venta where cliente_idcliente=vcliente and usuario_idusuario=vusuario); SET vinv = SUBSTRING(vinv, LOCATE(',',vinv) + 1); SET vcant = SUBSTRING(vcant, LOCATE(',',vcant) + 1); IF inv <> ',' THEN INSERT INTO detalle_venta(cant, venta_idventa, medicamento_idmedicamento) VALUES (can, id_ven, inv); UPDATE medicamento SET cant = inv_update WHERE idmedicamento = inv; END IF; END WHILE; SET res = 1; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `modificarCliente` (`vidcliente` INT, `vnombre` VARCHAR(45), `vapellido` VARCHAR(45), `vcedula` INT, `vgenero` VARCHAR(45), `vfecha_naci` DATE) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select cedula from cliente where cedula=vcedula and idcliente<>vidcliente) THEN update cliente set nombre=vnombre, apellido=vapellido, cedula=vcedula, genero=vgenero, fecha_naci=vfecha_naci where idcliente=vidcliente; set res = 1; END IF; RETURN res; END$$ CREATE FUNCTION modificarProveedor ( `vidproveedor` INT, `vnit` VARCHAR(45), `vnombre` VARCHAR(45), `vciudad` VARCHAR(45), `vdireccion` VARCHAR(45), `vtelefono` VARCHAR(45) ) RETURNS INT(1) READS SQL DATA DETERMINISTIC BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select nit from proveedor where nit=vnit and id<>vidproveedor) THEN update proveedor set nit=vnit, nombre=vnombre, ciudad=vciudad, direccion=vdireccion, telefono=vtelefono where id=vidproveedor; set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `modificarUsuario` (`vidusuario` INT, `vcedula` INT, `vnombre` VARCHAR(45), `vapellido` VARCHAR(45), `vcorreo` VARCHAR(45), `vtipoUsuario` INT, `vusuario` VARCHAR(45), `vpassword` INT) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select cedula from usuario where cedula=vcedula and idusuario<>vidusuario) THEN update usuario set cedula=vcedula, nombre=vnombre, apellido=vapellido, correo=vcorreo, tipoUsuario_idTipoUsuario=vtipoUsuario, usuario=vusuario, password=vpassword where idusuario=vidusuario; set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `modificarLaboratorio` (`vidlaboratorio` INT, `vnombre` VARCHAR(45), `vdescrip` VARCHAR(45)) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; IF NOT EXISTS(select idlaboratorio from laboratorio where idlaboratorio=vidlaboratorio and nombre<>vnombre) THEN update laboratorio set nombre=vnombre, descrip=vdescrip where idlaboratorio=vidlaboratorio; set res = 1; END IF; RETURN res; END$$ CREATE DEFINER=`root`@`localhost` FUNCTION `modificarEstante` (`videstante` INT, `vcodigo` VARCHAR(45), `vcategoria` VARCHAR(45), `vdescripcion` VARCHAR(45)) RETURNS INT(1) READS SQL DATA DETERMINISTIC COMMENT 'no se que estoy haciendo' BEGIN DECLARE res INT DEFAULT 0; -- select idestante from estante where idestante=videstante and codigo<>vcodigo IF NOT EXISTS(select codigo from estante where codigo=vcodigo and idestante<>videstante) THEN update estante set codigo=vcodigo, categoria=vcategoria, descripcion=vdescripcion where idestante=videstante; set res = 1; END IF; RETURN res; END$$ DELIMITER ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cliente` -- CREATE TABLE `cliente` ( `idcliente` int(11) NOT NULL, `nombre` varchar(45) DEFAULT NULL, `apellido` varchar(45) DEFAULT NULL, `cedula` varchar(45) DEFAULT NULL, `genero` varchar(45) DEFAULT NULL, `fecha_naci` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `cliente` -- INSERT INTO `cliente` (`idcliente`, `nombre`, `apellido`, `cedula`, `genero`, `fecha_naci`) VALUES (1, 'Jairo', 'Salazar', '12345', 'Masculino', '2032-02-02'), (2, 'willy', 'colon', '971', 'Masculino', '1987-03-12'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `detalle_venta` -- CREATE TABLE `detalle_venta` ( `iddetalle_venta` int(11) NOT NULL, `cant` int(11) DEFAULT NULL, `medicamento_idmedicamento` int(11) NOT NULL, `venta_idventa` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `detalle_venta` -- INSERT INTO `detalle_venta` (`iddetalle_venta`, `cant`, `medicamento_idmedicamento`, `venta_idventa`) VALUES (1, 1, 2, 5), (2, 1, 2, 6), (3, 1, 1, 7), (4, 1, 3, 7), (5, 2, 3, 8), (6, 1, 2, 9), (7, 1, 2, 10), (8, 2, 3, 10), (9, 1, 2, 11), (10, 1, 2, 12); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `laboratorio` -- CREATE TABLE `laboratorio` ( `idlaboratorio` int(11) NOT NULL, `nombre` varchar(45) DEFAULT NULL, `descrip` varchar(45) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `estante` -- CREATE TABLE `farmacia`.`estante` ( `idestante` INT NOT NULL AUTO_INCREMENT, `codigo` VARCHAR(45) NULL, `categoria` VARCHAR(45) NULL, `descripcion` VARCHAR(45) NULL, PRIMARY KEY (`idestante`), UNIQUE INDEX `codigo_UNIQUE` (`codigo` ASC)); -- CREATE TABLE `farmacia`.`estante` ( `idestante` INT(11) NOT NULL AUTO_INCREMENT , `codigo` VARCHAR(45) CHARACTER SET armscii8 COLLATE armscii8_general_ci NULL DEFAULT NULL , `categoria` VARCHAR(45) CHARACTER SET armscii8 COLLATE armscii8_general_ci NULL DEFAULT NULL , `descripcion` VARCHAR(45) CHARACTER SET armscii8 COLLATE armscii8_general_ci NULL DEFAULT NULL , PRIMARY KEY (`idestante`(11)), UNIQUE `indice_codigo` (`codigo`(45))) ENGINE = InnoDB; -- CREATE TABLE `estante` ( -- `idestante` int(11) NOT NULL, -- `codigo` varchar(45) DEFAULT NULL, -- `categoria` varchar(45) DEFAULT NULL, -- `descripcion` varchar(45) DEFAULT NULL -- ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `laboratorio` -- INSERT INTO `laboratorio` (`idlaboratorio`, `nombre`, `descrip`) VALUES (1, 'genfar', 'jajajajajajaja'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `medicamento` -- CREATE TABLE `medicamento` ( `idmedicamento` int(11) NOT NULL, `nombre` varchar(45) DEFAULT NULL, `descrip` varchar(45) DEFAULT NULL, `fecha_venc` date DEFAULT NULL, `cant` varchar(45) DEFAULT NULL, `fecha_creado` date DEFAULT NULL, `precio` int(11) DEFAULT NULL, `usuario_idusuario` int(11) NOT NULL, `laboratorio_idlaboratorio` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `medicamento` -- INSERT INTO `medicamento` (`idmedicamento`, `nombre`, `descrip`, `fecha_venc`, `cant`, `fecha_creado`, `precio`, `usuario_idusuario`, `laboratorio_idlaboratorio`) VALUES (1, 'ACETAMINOFEN', 'no sea', '2032-02-02', '0', '2020-02-02', 1, 13, 1), (2, 'IBUPRO', 'ajkn', '2019-12-31', '16', '2021-12-02', 55, 13, 1), (3, 'ADW', 'jn', '2017-12-31', '0', '2017-12-26', 100, 13, 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuario` -- CREATE TABLE `usuario` ( `idusuario` int(11) NOT NULL, `cedula` int(11) DEFAULT NULL, `nombre` varchar(45) DEFAULT NULL, `apellido` varchar(45) DEFAULT NULL, `correo` varchar(45) DEFAULT NULL, `tipoUsuario_idTipoUsuario` int(11) NOT NULL, `usuario` varchar(45) DEFAULT NULL, `password` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `usuario` -- INSERT INTO `usuario` (`idusuario`, `cedula`, `nombre`, `apellido`, `correo`, `tipoUsuario_idTipoUsuario`, `usuario`, `password`) VALUES (1, 1094, 'sebas', 'pala', 'sebas@pala.com', 1, 'admin', 123), (2, 1, 'Brian', 'Lopez', 'empl@asd.com', 2, 'empleado', 341), (3, 22, 'da', 'dwa', 'daw@as.com', 3, 'cliente', 34); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tipoUsuario` -- CREATE TABLE `tipoUsuario` ( `idTipoUsuario` int(11) NOT NULL, `nombre` varchar(45) DEFAULT NULL, PRIMARY KEY (`idTipoUsuario`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `tipoUsuario` -- INSERT INTO `tipoUsuario` (`idTipoUsuario`, `nombre`) VALUES (1, 'Administrador'), (2, 'Empleado'), (3, 'Cliente'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `venta` -- CREATE TABLE `venta` ( `idventa` int(11) NOT NULL, `fecha_venta` datetime DEFAULT NULL, `valor_total` int(11) DEFAULT NULL, `cliente_idcliente` int(11) NOT NULL, `usuario_idusuario` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `venta` -- INSERT INTO `venta` (`idventa`, `fecha_venta`, `valor_total`, `cliente_idcliente`, `usuario_idusuario`) VALUES (5, '2020-01-12', 55, 1, 13), (6, '2020-02-21', 55, 1, 13), (7, '2020-03-27', 101, 1, 13), (8, '2020-04-01', 55, 2, 13), (9, '2020-09-23', 255, 1, 13), (10, '2020-11-12', 55, 2, 13), (11, '2020-12-31', 55, 1, 13), (12, '2017-12-31', 55, 1, 13); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `cliente` -- ALTER TABLE `cliente` ADD PRIMARY KEY (`idcliente`); -- -- Indices de la tabla `detalle_venta` -- ALTER TABLE `detalle_venta` ADD PRIMARY KEY (`iddetalle_venta`), ADD KEY `medicamento_idmedicamento` (`medicamento_idmedicamento`), ADD KEY `venta_idventa` (`venta_idventa`); -- -- Indices de la tabla `laboratorio` -- ALTER TABLE `laboratorio` ADD PRIMARY KEY (`idlaboratorio`); -- -- Indices de la tabla `medicamento` -- ALTER TABLE `medicamento` ADD PRIMARY KEY (`idmedicamento`), ADD KEY `usuario_idusuario` (`usuario_idusuario`), ADD KEY `laboratorio_idlaboratorio` (`laboratorio_idlaboratorio`); -- tipoUsuario -- Indices de la tabla `tipoUsuario` -- ALTER TABLE `tipoUsuario` ADD PRIMARY KEY (`idTipoUsuario`); -- -- Indices de la tabla `usuario` -- ALTER TABLE `usuario` ADD PRIMARY KEY (`idusuario`), ADD KEY `tipoUsuario_idTipoUsuario` (`tipoUsuario_idTipoUsuario`); -- -- Indices de la tabla `venta` -- ALTER TABLE `venta` ADD PRIMARY KEY (`idventa`), ADD KEY `cliente_idcliente` (`cliente_idcliente`), ADD KEY `usuario_idusuario` (`usuario_idusuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `cliente` -- ALTER TABLE `cliente` MODIFY `idcliente` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT de la tabla `detalle_venta` -- ALTER TABLE `detalle_venta` MODIFY `iddetalle_venta` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT de la tabla `laboratorio` -- ALTER TABLE `laboratorio` MODIFY `idlaboratorio` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT de la tabla `medicamento` -- ALTER TABLE `medicamento` MODIFY `idmedicamento` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `usuario` -- ALTER TABLE `usuario` MODIFY `idusuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- tipoUsuario -- AUTO_INCREMENT de la tabla `tipoUsuario` -- ALTER TABLE `tipoUsuario` MODIFY `idTipoUsuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `venta` -- ALTER TABLE `venta` MODIFY `idventa` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `detalle_venta` -- ALTER TABLE `detalle_venta` ADD CONSTRAINT `detalle_venta_ibfk_1` FOREIGN KEY (`medicamento_idmedicamento`) REFERENCES `medicamento` (`idmedicamento`), ADD CONSTRAINT `detalle_venta_ibfk_2` FOREIGN KEY (`venta_idventa`) REFERENCES `venta` (`idventa`); -- -- Filtros para la tabla `medicamento` -- ALTER TABLE `medicamento` ADD CONSTRAINT `medicamento_ibfk_1` FOREIGN KEY (`usuario_idusuario`) REFERENCES `usuario` (`idusuario`), ADD CONSTRAINT `medicamento_ibfk_2` FOREIGN KEY (`laboratorio_idlaboratorio`) REFERENCES `laboratorio` (`idlaboratorio`); -- -- Filtros para la tabla `venta` -- ALTER TABLE `venta` ADD CONSTRAINT `venta_ibfk_1` FOREIGN KEY (`cliente_idcliente`) REFERENCES `cliente` (`idcliente`), ADD CONSTRAINT `venta_ibfk_2` FOREIGN KEY (`usuario_idusuario`) REFERENCES `usuario` (`idusuario`); COMMIT; -- -- Filtros para la tabla `usuario` -- ALTER TABLE `usuario` ADD CONSTRAINT `usuario_ibfk_1` FOREIGN KEY (`tipoUsuario_idTipoUsuario`) REFERENCES `tipoUsuario` (`idTipoUsuario`); 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
bdac2b8917ca41e38760cd2017f02498ddea0e45
SQL
francobustos/BaseDeDatos2
/ejercicio11.sql
UTF-8
1,793
4.65625
5
[]
no_license
-- Find all the film titles that are not in the inventory. SELECT f.title, i.* FROM film f LEFT JOIN inventory i inventory_id IS NULL; -- Find all the films that are in the inventory but were never rented. -- Show title and inventory_id. SELECT f.title, i.inventory_id FROM film f INNER JOIN inventory i USING (film_id) LEFT JOIN rental r USING (inventory_id) WHERE r.inventory_id IS NULL; -- Generate a report with: customer (first, last) name, store id, film title, -- when the film was rented and returned for each of these customers. Order by store_id, customer last_name SELECT CONCAT(c.last_name, ' ', c.first_name) as name, i.store_id, f.title, r.rental_date, r.return_date FROM customer c INNER JOIN rental r USING (customer_id) INNER JOIN inventory i USING (inventory_id) INNER JOIN film f USING (film_id) ORDER BY i.store_id, c.last_name -- Show sales per store (money of rented films) -- show store's city, country, manager info and total sales (money) -- (optional) Use concat to show city and country and manager first and last name SELECT s.store_id, CONCAT(ci.city, ", ", co.country) as location, CONCAT(m.first_name, " ", m.last_name) as manager, sum(amount) as sales FROM store s INNER JOIN address USING (address_id) INNER JOIN city ci USING (city_id) INNER JOIN country co USING (country_id) INNER JOIN staff m ON s.manager_staff_id = m.staff_id INNER JOIN payment USING (staff_id) GROUP BY s.store_id; -- Which actor has appeared in the most films? SELECT a.actor_id, a.first_name, a.last_name, COUNT(fa.film_id) AS peliculas_actuadas FROM actor a INNER JOIN film_actor fa USING (actor_id) GROUP BY a.actor_id HAVING peliculas_actuadas >= ALL( SELECT COUNT(film_id) FROM film_actor GROUP BY actor_id);
true
58ced0196f5217b590ea84b63fba5bd83d6d0b5d
SQL
D-YSF-A/FoodyApp
/sql/create_item_table.sql
UTF-8
556
3.046875
3
[ "Apache-2.0" ]
permissive
CREATE TABLE public."items" ( id serial, name character varying, price integer, imgUrl character varying, category character varying, location point, restorantId serial, description character varying, PRIMARY KEY (id) ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; ALTER TABLE public."items" OWNER to postgres; ALTER TABLE "public"."items" ADD COLUMN "description" character varying; ALTER TABLE "public"."items" ADD FOREIGN KEY ("restorantId") REFERENCES "public"."items"("id") ON DELETE CASCADE;
true
9f4639d86b23d42be47ef201da4b8425ae03b3f5
SQL
krissy16/dream-diary-api
/migrations/002.do.create_dreams.sql
UTF-8
250
2.828125
3
[]
no_license
CREATE TABLE dreams ( id SERIAL PRIMARY KEY, title TEXT NOT NULL, date_created date DEFAULT now(), content TEXT NOT NULL, notes TEXT, archived BOOLEAN DEFAULT false, user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL );
true
cf09d30bb2492d20e5182f59379654bac0b0e46e
SQL
jeremGoulier/geektic2014
/database/script.sql
UTF-8
2,830
3.75
4
[]
no_license
/*Suppression des tables*/ DROP TABLE CENTRE_INTERET; DROP TABLE CONSULTATION; DROP TABLE UTILISATEUR; /*Création de la table utilisateur*/ create table UTILISATEUR ( id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1 , INCREMENT BY 1) not null, nom varchar(40) not null, prenom varchar(40) not null, age integer not null, mail varchar(150) not null, sexe varchar (40) not null, CI integer not null, constraint pk_utilisateur_id primary key(id) ); /*Création de la table Consultation*/ create table CONSULTATION( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1 , INCREMENT BY 1 ) not null , id_utilisateur_consulte integer not null, adresse_ip_visiteur varchar(11) not null, date_visite datetime not null, constraint pk_consultation_id primary key(id) ); /*Création de la table Centre_interet*/ create table CENTRE_INTERET( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1 , INCREMENT BY 1 ) not null, libelle varchar(50) not null, constraint pk_centre_interet_id primary key(id) ); /*Ajout de contraintes*/ alter table CONSULTATION add constraint fk_consultation_id_utilisateur_consulte foreign key(id_utilisateur_consulte) REFERENCES UTILISATEUR(id); alter table UTILISATEUR add constraint fk_user_CI foreign key(CI) REFERENCES CENTRE_INTERET(ID); /*Insertion dans la table centre interet*/ INSERT INTO "PUBLIC"."CENTRE_INTERET" ( "ID", "LIBELLE" ) VALUES ('1', 'Java'); INSERT INTO "PUBLIC"."CENTRE_INTERET" ( "ID", "LIBELLE" ) VALUES ('2', 'PHP'); INSERT INTO "PUBLIC"."CENTRE_INTERET" ( "ID", "LIBELLE" ) VALUES ('3', 'C#'); INSERT INTO "PUBLIC"."CENTRE_INTERET" ( "ID", "LIBELLE" ) VALUES ('4', 'TDD'); INSERT INTO "PUBLIC"."CENTRE_INTERET" ( "ID", "LIBELLE" ) VALUES ('5', 'Junit'); /*Insertion dans la table utilsiateur*/ INSERT INTO "PUBLIC"."UTILISATEUR" ("NOM", "PRENOM", "AGE", "MAIL", "SEXE", "CI" ) VALUES ('Goulier', 'Jérémy', '21', 'j.goulier@orange.fr','homme','1'); INSERT INTO "PUBLIC"."UTILISATEUR" ("NOM", "PRENOM", "AGE", "MAIL", "SEXE", "CI" ) VALUES ('Olivo', 'Martin', '21', 'martinator@hotmail.fr','homme','2'); INSERT INTO "PUBLIC"."UTILISATEUR" ("NOM", "PRENOM", "AGE", "MAIL", "SEXE", "CI" ) VALUES ('Dufour', 'Pierre', '22', 'pierre.dufour@sfr.com', 'homme','3'); INSERT INTO "PUBLIC"."UTILISATEUR" ("NOM", "PRENOM", "AGE", "MAIL", "SEXE", "CI" ) VALUES ('Garel', 'Lorraine', '25', 'lorraine.garel@free.fr', 'femme','4'); INSERT INTO "PUBLIC"."UTILISATEUR" ("NOM", "PRENOM", "AGE", "MAIL", "SEXE", "CI" ) VALUES ('Lespect', 'Jo', '27', 'j.lespect@orange.fr','homme','1'); INSERT INTO "PUBLIC"."UTILISATEUR" ("NOM", "PRENOM", "AGE", "MAIL", "SEXE", "CI" ) VALUES ('Affou', 'Adam', '21', 'adamaffou@orange.fr','homme','1'); INSERT INTO "PUBLIC"."UTILISATEUR" ("NOM", "PRENOM", "AGE", "MAIL", "SEXE", "CI" ) VALUES ('Vautard', 'Florian', '23', 'vf@orange.fr','homme','2');
true
d5fec8702e7a312ec09475f5ef15715c6d7bd974
SQL
balapkm/Juntos
/application/databases/juntos_V11.sql
UTF-8
12,170
3.25
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
-- Adminer 4.6.2 MySQL dump SET NAMES utf8; SET time_zone = '+00:00'; SET foreign_key_checks = 0; SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'; DROP TABLE IF EXISTS `article_details`; CREATE TABLE `article_details` ( `article_id` int(11) NOT NULL AUTO_INCREMENT, `article_name` varchar(50) NOT NULL, `status` enum('Y','N') NOT NULL, PRIMARY KEY (`article_id`), UNIQUE KEY `article_name` (`article_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `color_details`; CREATE TABLE `color_details` ( `color_id` int(11) NOT NULL AUTO_INCREMENT, `color_name` varchar(50) NOT NULL, `status` enum('Y','N') NOT NULL, PRIMARY KEY (`color_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `component_details`; CREATE TABLE `component_details` ( `component_id` int(11) NOT NULL AUTO_INCREMENT, `user_group_id` int(11) NOT NULL, `component_name` varchar(50) NOT NULL, `component_outlet` varchar(10) NOT NULL, `component_file_path` varchar(50) NOT NULL, `component_path` varchar(50) NOT NULL, `status` enum('Y','N') NOT NULL, PRIMARY KEY (`component_id`), KEY `user_group_id` (`user_group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `component_details` (`component_id`, `user_group_id`, `component_name`, `component_outlet`, `component_file_path`, `component_path`, `status`) VALUES (1, 1, 'MasterEntry', 'div1', '', 'master-entry', 'Y'), (2, 1, 'DataEntry', 'div1', '', 'data-entry', 'Y'), (3, 1, 'Report', 'div1', '', 'report', 'Y'), (4, 1, 'PoMasterEntry', 'div1', '', 'po_master_entry', 'Y'), (5, 1, 'GeneratePo', 'div1', '', 'generate_po', 'Y'), (6, 1, 'MaterialOutstanding', 'div1', '', 'material_outstanding', 'Y'), (7, 1, 'PaymentBook', 'div1', '', 'payment_book', 'Y'); DROP TABLE IF EXISTS `data_entry`; CREATE TABLE `data_entry` ( `data_entry_id` int(11) NOT NULL AUTO_INCREMENT, `serial_no` int(11) NOT NULL, `article_id` int(11) NOT NULL, `color_id` int(11) NOT NULL, `selection_id` int(11) NOT NULL, `description_id` int(11) NOT NULL, `date` date NOT NULL, `leather` varchar(50) NOT NULL, `query` varchar(50) NOT NULL, `pieces` float NOT NULL, `sqfeet` float NOT NULL, `remarks` text NOT NULL, `status` enum('Y','N') NOT NULL DEFAULT 'Y', PRIMARY KEY (`data_entry_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `debit_note_details`; CREATE TABLE `debit_note_details` ( `s_no` int(11) NOT NULL AUTO_INCREMENT, `supplier_id` int(11) NOT NULL, `type` char(1) NOT NULL, `debit_note_no` varchar(30) NOT NULL, `debit_note_date` date NOT NULL, `supplier_creditnote` varchar(30) NOT NULL, `supplier_creditnote_date` varchar(30) NOT NULL, `query` varchar(30) NOT NULL, `payable_month` varchar(30) NOT NULL, `amount` float NOT NULL, `created_date` date NOT NULL, PRIMARY KEY (`s_no`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `description_details`; CREATE TABLE `description_details` ( `description_id` int(11) NOT NULL AUTO_INCREMENT, `description_name` varchar(50) NOT NULL, `status` enum('Y','N') NOT NULL, PRIMARY KEY (`description_id`), UNIQUE KEY `description_name` (`description_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `import_other_details`; CREATE TABLE `import_other_details` ( `import_other_id` int(11) NOT NULL AUTO_INCREMENT, `unit` varchar(30) NOT NULL, `type` varchar(30) NOT NULL, `po_number` varchar(30) NOT NULL, `po_date` date NOT NULL, `delivery_date` date NOT NULL, `incoterms` varchar(50) NOT NULL, `payment_terms` varchar(50) NOT NULL, `Shipment` varchar(50) NOT NULL, PRIMARY KEY (`import_other_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `material_details`; CREATE TABLE `material_details` ( `material_id` int(11) NOT NULL AUTO_INCREMENT, `supplier_id` int(11) NOT NULL, `material_master_id` int(11) NOT NULL, `material_name` varchar(100) NOT NULL, `group` varchar(30) NOT NULL, `material_hsn_code` varchar(30) NOT NULL, `material_uom` varchar(30) NOT NULL, `currency` varchar(10) NOT NULL, `price` float NOT NULL, `price_status` varchar(30) NOT NULL, `CGST` float NOT NULL, `SGST` float NOT NULL, `IGST` float NOT NULL, `discount` float NOT NULL, `discount_price_status` enum('PERCENTAGE','AMOUNT') NOT NULL DEFAULT 'PERCENTAGE', `status` enum('Y','N') NOT NULL, PRIMARY KEY (`material_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `material_master`; CREATE TABLE `material_master` ( `material_id` int(11) NOT NULL AUTO_INCREMENT, `material_name` varchar(200) NOT NULL, `status` enum('Y','N') NOT NULL DEFAULT 'Y', PRIMARY KEY (`material_id`), UNIQUE KEY `material_name` (`material_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `menu_details`; CREATE TABLE `menu_details` ( `menu_id` int(11) NOT NULL AUTO_INCREMENT, `menu_name` varchar(100) NOT NULL, `menu_link` varchar(100) NOT NULL DEFAULT '#', `menu_icon` varchar(100) NOT NULL, `menu_active` varchar(10) NOT NULL, `menu_status` varchar(3) NOT NULL DEFAULT 'Y', PRIMARY KEY (`menu_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `menu_details` (`menu_id`, `menu_name`, `menu_link`, `menu_icon`, `menu_active`, `menu_status`) VALUES (1, 'Leather Details', '#', '', 'active', 'Y'), (2, 'Purchase Order', '#', '', '', 'Y'); DROP TABLE IF EXISTS `menu_sub_menu_mapping_details`; CREATE TABLE `menu_sub_menu_mapping_details` ( `sub_menu_mapping_id` int(11) NOT NULL AUTO_INCREMENT, `menu_id` int(11) NOT NULL, `user_group_id` int(11) NOT NULL, `sub_menu_id` int(11) NOT NULL, PRIMARY KEY (`sub_menu_mapping_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `menu_sub_menu_mapping_details` (`sub_menu_mapping_id`, `menu_id`, `user_group_id`, `sub_menu_id`) VALUES (1, 1, 1, 1), (2, 1, 1, 2), (3, 1, 1, 3), (4, 2, 1, 4), (5, 2, 1, 5), (6, 2, 1, 6), (7, 2, 1, 7); DROP TABLE IF EXISTS `other_master_details`; CREATE TABLE `other_master_details` ( `other_master_id` int(11) NOT NULL AUTO_INCREMENT, `type` enum('GROUP') NOT NULL, `name` varchar(100) NOT NULL, `status` enum('Y','N') NOT NULL DEFAULT 'Y', PRIMARY KEY (`other_master_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `overall_discount_details`; CREATE TABLE `overall_discount_details` ( `overall_discount_id` int(11) NOT NULL AUTO_INCREMENT, `unit` varchar(20) NOT NULL, `type` varchar(20) NOT NULL, `po_number` int(11) NOT NULL, `po_date` date NOT NULL, `discount_type` enum('PERCENTAGE','AMOUNT') NOT NULL DEFAULT 'PERCENTAGE', `discount` float NOT NULL, PRIMARY KEY (`overall_discount_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `po_generated_request_details`; CREATE TABLE `po_generated_request_details` ( `po_generated_request_id` int(11) NOT NULL AUTO_INCREMENT, `parent_po_generated_request_id` int(11) NOT NULL, `unit` varchar(30) NOT NULL, `type` varchar(30) NOT NULL, `order_reference` varchar(30) NOT NULL, `po_number` varchar(30) NOT NULL, `po_date` date NOT NULL, `delivery_date` date NOT NULL, `supplier_id` int(11) NOT NULL, `material_id` int(11) NOT NULL, `material_master_id` int(11) NOT NULL, `material_name` varchar(300) NOT NULL, `po_description` varchar(300) NOT NULL, `material_hsn_code` varchar(30) NOT NULL, `qty` float NOT NULL, `material_uom` varchar(30) NOT NULL, `currency` varchar(30) NOT NULL, `price` float NOT NULL, `price_status` varchar(30) NOT NULL, `CGST` float NOT NULL, `IGST` float NOT NULL, `SGST` float NOT NULL, `discount` float NOT NULL, `discount_price_status` enum('PERCENTAGE','AMOUNT') NOT NULL DEFAULT 'PERCENTAGE', `received` int(11) NOT NULL, `received_date` date NOT NULL, `dc_date` date NOT NULL, `bill_date` date NOT NULL, `bill_number` varchar(50) NOT NULL, `bill_amount` float NOT NULL, `payable_month` date NOT NULL, `dc_number` varchar(30) NOT NULL, `avg_cost` varchar(50) NOT NULL, `deduction` varchar(100) NOT NULL, `cheque_no` varchar(100) NOT NULL, `cheque_date` date NOT NULL, `cheque_amount` float NOT NULL, `outstanding_type` enum('M','B') NOT NULL DEFAULT 'M', `created_date` date NOT NULL, `s_no` int(11) NOT NULL, `query` varchar(50) NOT NULL, PRIMARY KEY (`po_generated_request_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `po_other_additional_charges`; CREATE TABLE `po_other_additional_charges` ( `po_other_additional_id` int(11) NOT NULL AUTO_INCREMENT, `unit` varchar(50) NOT NULL, `type` varchar(50) NOT NULL, `po_number` int(11) NOT NULL, `po_date` date NOT NULL, `name` varchar(100) NOT NULL, `hsn_code` varchar(100) NOT NULL, `amount_type` enum('PERCENTAGE','AMOUNT') NOT NULL DEFAULT 'PERCENTAGE', `amount` float NOT NULL, `CGST` float NOT NULL, `SGST` float NOT NULL, `IGST` float NOT NULL, `created_date` date NOT NULL, `status` enum('Y','N') NOT NULL, PRIMARY KEY (`po_other_additional_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `selection_details`; CREATE TABLE `selection_details` ( `selection_id` int(11) NOT NULL AUTO_INCREMENT, `selection_name` varchar(50) NOT NULL, `status` enum('Y','N') NOT NULL, PRIMARY KEY (`selection_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `sub_menu_details`; CREATE TABLE `sub_menu_details` ( `sub_menu_id` int(11) NOT NULL AUTO_INCREMENT, `sub_menu_name` varchar(100) NOT NULL, `sub_menu_link` varchar(100) NOT NULL DEFAULT '#', `sub_menu_icon` varchar(100) NOT NULL, `sub_menu_status` varchar(3) NOT NULL DEFAULT 'Y', PRIMARY KEY (`sub_menu_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `sub_menu_details` (`sub_menu_id`, `sub_menu_name`, `sub_menu_link`, `sub_menu_icon`, `sub_menu_status`) VALUES (1, 'Master Entry', 'master-entry', '', 'Y'), (2, 'Data Entry', 'data-entry', '', 'Y'), (3, 'Report', 'report', '', 'Y'), (4, 'Master Entry', 'po_master_entry', '', 'Y'), (5, 'Generate Po', 'generate_po', '', 'Y'), (6, 'Material and Bill Outstanding', 'material_outstanding', '', 'Y'), (7, 'Payment Book', 'payment_book', '', 'Y'); DROP TABLE IF EXISTS `supplier_details`; CREATE TABLE `supplier_details` ( `supplier_id` int(11) NOT NULL AUTO_INCREMENT, `supplier_name` varchar(100) NOT NULL, `supplier_code` varchar(50) NOT NULL, `alt_supplier_name` varchar(100) NOT NULL, `supplier_address` text NOT NULL, `alt_supplier_address` text NOT NULL, `contact_no` varchar(50) NOT NULL, `email_id` varchar(150) NOT NULL, `origin` varchar(100) NOT NULL, `gst_no` varchar(100) NOT NULL, `state_code` varchar(5) NOT NULL, `supplier_tax_status` varchar(30) NOT NULL, `supplier_status` varchar(30) NOT NULL, `bank_details` text NOT NULL, `status` enum('Y','N') NOT NULL DEFAULT 'Y', PRIMARY KEY (`supplier_id`), UNIQUE KEY `supplier_name` (`supplier_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `uof_master`; CREATE TABLE `uof_master` ( `uof_id` int(11) NOT NULL AUTO_INCREMENT, `uof_name` varchar(30) NOT NULL, `uof_status` enum('Y','N') NOT NULL DEFAULT 'Y', PRIMARY KEY (`uof_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `user_group_details`; CREATE TABLE `user_group_details` ( `user_group_id` int(11) NOT NULL AUTO_INCREMENT, `user_group_name` varchar(10) NOT NULL, `user_group_status` enum('Y','N') NOT NULL, PRIMARY KEY (`user_group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `user_group_details` (`user_group_id`, `user_group_name`, `user_group_status`) VALUES (1, 'admin', 'Y'); DROP TABLE IF EXISTS `user_login_details`; CREATE TABLE `user_login_details` ( `user_login_id` int(11) NOT NULL AUTO_INCREMENT, `user_group_id` int(11) NOT NULL, `user_login_name` varchar(50) NOT NULL, `user_login_password` varchar(200) NOT NULL, `user_status` enum('Y','N') NOT NULL, PRIMARY KEY (`user_login_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `user_login_details` (`user_login_id`, `user_group_id`, `user_login_name`, `user_login_password`, `user_status`) VALUES (1, 1, 'admin', 'e6e061838856bf47e1de730719fb2609', 'Y'); -- 2018-04-15 12:49:29
true
cd0f9b43e0266e159a72030240ac776ce07ffa3c
SQL
Aper99/Base-de-Datos-I
/problema_20.sql
UTF-8
587
3.046875
3
[]
no_license
-- 1 drop table if exists peliculas; -- 2 create table peliculas( codigo int unsigned auto_increment, titulo varchar(30) not null, actor varchar(20), duracion tinyint unsigned, primary key(codigo) ); -- 3 insert into peliculas (titulo,actor,duracion) values('Mision imposible','Tom Cruise',120); insert into peliculas (codigo,duracion) values(5,90); insert into peliculas (titulo,actor) values('Harry Potter y la piedra filosofal','Daniel R.'); insert into peliculas (titulo,actor,duracion) values ('Harry Potter y la piedra filosofal','Daniel R.',120); -- 4 select * from peliculas;
true
390ffdc22c3e00bb199d8474ef040c11c1d8c9b5
SQL
Enin/mysql_training
/thinkSQL/생각대로SQL8 - 문제리스트.sql
UHC
5,984
4.15625
4
[]
no_license
1) dvd 뿩 ̸? (analytic funtion Ȱ) SELECT c.customer_id , c.first_name , c.last_name , COUNT(r.rental_id) AS CNT , ROW_NUMBER() OVER( ORDER BY COUNT(r.rental_id) DESC ) AS RANKS FROM rental r JOIN customer c ON r.customer_id = c.customer_id GROUP BY c.customer_id LIMIT 1; 2) ø dvd ̸? (analytic funtion Ȱ) Ǯ -- RANK : 1, 1, 3, 4, ... -- PERCENT_RANK : -- DENSE_RANK : 1, 1, 2, 3, ... -- ROW_NUMBER : 1, 2, 3, 4, ... SELECT c.customer_id , c.first_name , c.last_name , SUM(amount) AS SUM_AMT , RANK() OVER( ORDER BY SUM(amount) DESC ) AS RANKING FROM customer c JOIN payment p ON c.customer_id = p.customer_id GROUP BY c.customer_id LIMIT 1; 3) dvd 뿩 ô? (anlytic funtion) SELECT c2.city_id , c2.city , COUNT(r.rental_id) AS CNT , RANK() OVER( ORDER BY COUNT(r.rental_id) ASC) AS RANKING FROM rental r JOIN customer c ON r.customer_id = c.customer_id JOIN address a ON c.address_id = a.address_id JOIN city c2 ON a.city_id = c2.city_id GROUP BY c2.city_id LIMIT 1; SELECT * FROM city c ; 4) ȳ ô? (anlytic funtion) SELECT c2.city_id , c2.city , SUM(p.amount) AS A_SUM , DENSE_RANK() OVER( ORDER BY SUM(p.amount) ) AS RANKING FROM payment p JOIN customer c ON p.customer_id = c.customer_id JOIN address a ON c.address_id = a.address_id JOIN city c2 ON a.city_id = c2.city_id GROUP BY c2.city_id LIMIT 1; 5) ϰ پ ϼ. (ڴ payment_date ) Ǯ SELECT * FROM ( SELECT EXTRACT(YEAR FROM DATE(p.PAYMENT_DATE)) AS YR, -- EXTRACT Լ DATE(P.PAYMENT_DATE) YEAR, MONTH, DAY ¥ ãƿ EXTRACT(MONTH FROM DATE(p.PAYMENT_DATE)) AS MON, -- TO_CHAR(P.PAYMENT_DATE, 'YYYY') ص . SUM(p.AMOUNT) AS SUM_AMOUNT , COALESCE( LAG(SUM(p.AMOUNT), 1) OVER( ORDER BY EXTRACT(YEAR FROM DATE(p.PAYMENT_DATE))) , 0) AS PRE_MON_AMOUNT , SUM(p.AMOUNT) - COALESCE( LAG(SUM(p.AMOUNT), 1) OVER( ORDER BY EXTRACT(YEAR FROM DATE(p.PAYMENT_DATE))) , 0) AS GAP FROM payment p GROUP BY EXTRACT(YEAR FROM DATE(p.PAYMENT_DATE)) , EXTRACT(MONTH FROM DATE(p.PAYMENT_DATE)) ) AS DB WHERE GAP < 0 ; SELECT * FROM ( SELECT EXTRACT(YEAR FROM DATE(p.PAYMENT_DATE)) AS YR, -- EXTRACT Լ DATE(P.PAYMENT_DATE) YEAR, MONTH, DAY ¥ ãƿ EXTRACT(MONTH FROM DATE(p.PAYMENT_DATE)) AS MON, -- TO_CHAR(P.PAYMENT_DATE, 'YYYY') ص . SUM(p.AMOUNT) AS SUM_AMOUNT , COALESCE( LAG(SUM(p.AMOUNT), 1) OVER( ORDER BY EXTRACT(YEAR FROM DATE(p.PAYMENT_DATE))) , 0) AS PRE_MON_AMOUNT FROM payment p GROUP BY EXTRACT(YEAR FROM DATE(p.PAYMENT_DATE)) , EXTRACT(MONTH FROM DATE(p.PAYMENT_DATE)) ) AS DB WHERE sum_amount < pre_mon_amount ; 6) ú dvd 뿩 ϼ. SELECT c2.city_id , c2.city , SUM(p.amount) AS A_SUM , ROW_NUMBER () OVER ( ORDER BY SUM(p.amount) DESC ) AS RANKING FROM payment p JOIN customer c ON p.customer_id = c.customer_id JOIN address a ON c.address_id = a.address_id JOIN city c2 ON a.city_id = c2.city_id GROUP BY c2.city_id ; 7) 뿩 ϼ. Ǯ SELECT i.store_id , SUM(p.amount) AS SUM_AMOUNT , ROW_NUMBER () OVER ( ORDER BY SUM(p.amount) DESC ) AS SUM_AMOUNT_RANK FROM payment p JOIN rental r ON p.rental_id = r.rental_id JOIN inventory i ON r.inventory_id = i.inventory_id GROUP BY i.store_id ; 8) 󺰷 뿩 TOP 5 ϼ. -- 뿩 Ƚ ŷ SELECT * FROM( SELECT db.country, db.first_name, db.last_name, COUNT(DISTINCT db.rental_id) as rental_cnt , ROW_NUMBER () OVER ( PARTITION BY db.country ORDER BY COUNT(DISTINCT db.rental_id) DESC) AS RANKING FROM( -- 1 ʿ ü SELECT c3.country_id , c3.country , c.customer_id , c.first_name , c.last_name , r.rental_id FROM rental r JOIN customer c ON r.customer_id = c.customer_id JOIN address a ON c.address_id = a.address_id JOIN city c2 ON a.city_id = c2.city_id JOIN country c3 ON c2.country_id = c3.country_id ) AS db GROUP BY db.country, db.first_name, db.last_name ) AS db2 WHERE db2.ranking <= 5 ; 9) ȭ īװ (Category) 뿩 ȭ TOP 5 ϼ Ǯ SELECT * FROM ( SELECT DB.NAME, DB.TITLE , COUNT(DISTINCT DB.RENTAL_ID) AS CNT , ROW_NUMBER() OVER( PARTITION BY DB.NAME ORDER BY COUNT(DISTINCT DB.RENTAL_ID) DESC, DB.TITLE ASC ) AS RANKING -- īװ: PARTITION BY FROM ( SELECT r.rental_id , i.film_id , f.title , fc.category_id , c."name" FROM rental r JOIN inventory i ON r.inventory_id = i.inventory_id JOIN film f ON i.film_id = f.film_id JOIN film_category fc ON i.film_id = fc.film_id JOIN category c ON fc.category_id = c.category_id ) AS DB GROUP BY DB.NAME, DB.TITLE ) AS DB2 WHERE RANKING <= 5 ; 10) ȭ īװ ȭ īװ ϼ. (first_value, last_value) Ǯ SELECT * FROM ( SELECT c."name", SUM(p.amount) AS SUM_AMT , FIRST_VALUE(c."name") OVER (ORDER BY SUM(p.amount) ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS FIRST_VALUES, LAST_VALUE (c."name") OVER (ORDER BY SUM(p.amount) ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS LAST_VALUES -- . FROM payment p JOIN rental r ON p.rental_id = r.rental_id JOIN inventory i ON r.inventory_id = i.inventory_id JOIN film f ON i.film_id = f.film_id JOIN film_category fc ON i.film_id = fc.film_id JOIN category c ON fc.category_id = c.category_id GROUP BY c."name" ) AS DB WHERE NAME IN (FIRST_VALUES, LAST_VALUES);
true
835942e59c77f2894b45a664c871716b25047058
SQL
DenisKvashnin/atom
/backend/atom-hackaton/src/main/resources/db/changelog/changes/9-okved_2_outer_type.sql
UTF-8
2,304
2.640625
3
[]
no_license
CREATE TABLE IF NOT EXISTS okved_2_outer_type ( id bigint, okved_code character varying, org_type_id bigint ); CREATE SEQUENCE okved_2_outer_type_seq; ALTER SEQUENCE okved_2_outer_type_seq OWNED BY okved_2_outer_type.id; ALTER TABLE okved_2_outer_type ALTER COLUMN id SET DEFAULT nextval('okved_2_outer_type_seq'::regclass); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.11', 1); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.12', 7); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.13', 7); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.14', 7); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.21', 5); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.22', 2); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.22.1', 2); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.22.2', 2); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.22.3', 2); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.23', 2); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.3', 5); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.30', 5); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.4', 3); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.41', 3); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.41', 6); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.41.1', 3); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.41.1', 6); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.41.2', 3); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.41.9', 3); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.41.9', 6); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.41.91', 6); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.42', 3); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.42.1', 3); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.42.2', 3); INSERT INTO okved_2_outer_type(okved_code, org_type_id) VALUES ('85.42.9', 3);
true
89623c41b328e11a8921357689eaf0e7ea4b60fa
SQL
geotim90/Nevini
/src/main/resources/db/migration/V4_3_0__alter_activity.sql
UTF-8
340
3.390625
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
-- id for "online" activity should always be -1 UPDATE activity SET id = -1 WHERE type = 1; -- add source column to activity table and include in primary key ALTER TABLE activity DROP PRIMARY KEY; ALTER TABLE activity ADD COLUMN source BIGINT NOT NULL DEFAULT -1; ALTER TABLE activity ADD PRIMARY KEY (user, type, id, source);
true
93d01de2dc35a8a68695ab4f99e947424be2ed74
SQL
TangXW777/Paging
/lrfbeyond_demo.sql
UTF-8
8,668
2.875
3
[]
no_license
/* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Version : 50711 Source Host : localhost:3306 Source Database : lrfbeyond_demo Target Server Type : MYSQL Target Server Version : 50711 File Encoding : 65001 Date: 2016-10-31 12:20:21 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `article` -- ---------------------------- DROP TABLE IF EXISTS `article`; CREATE TABLE `article` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(100) NOT NULL, `pubdate` int(10) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=231 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of article -- ---------------------------- INSERT INTO `article` VALUES ('187', 'HTML5应用之时钟', '1346856092'); INSERT INTO `article` VALUES ('150', '自适应的网格布局-砌墙效果', '1322294653'); INSERT INTO `article` VALUES ('151', '图片延迟加载技术-Lazyload的应用', '1323418419'); INSERT INTO `article` VALUES ('152', '滚屏加载--无刷新动态加载数据技术的应用', '1324715776'); INSERT INTO `article` VALUES ('153', 'Ajax应用:使用jQuery和PHP实现功能开关效果', '1325776451'); INSERT INTO `article` VALUES ('154', 'Flowplayer-一款免费的WEB视频播放器', '1326016920'); INSERT INTO `article` VALUES ('155', 'Highcharts-功能强大的图表库的应用', '1326522351'); INSERT INTO `article` VALUES ('156', 'Highcharts选项配置详细说明文档', '1326719630'); INSERT INTO `article` VALUES ('157', '使用Highcharts生成折线图与曲线图', '1326895515'); INSERT INTO `article` VALUES ('158', '使用Highcharts生成柱状图', '1327025096'); INSERT INTO `article` VALUES ('159', '使用Highcharts结合PHP与Mysql生成饼状图', '1327918320'); INSERT INTO `article` VALUES ('160', '使用Highcharts实现柱状图、饼状图、曲线图三图合一', '1329039730'); INSERT INTO `article` VALUES ('161', 'jqGrid:强大的表格插件的应用', '1330074189'); INSERT INTO `article` VALUES ('162', 'jqGrid中文说明文档——选项设置', '1330234635'); INSERT INTO `article` VALUES ('163', 'jqGrid中文说明文档——事件和方法', '1330318428'); INSERT INTO `article` VALUES ('164', 'jqGrid表格应用——读取与查询数据', '1330591560'); INSERT INTO `article` VALUES ('165', 'jqGrid表格应用——新增与删除数据', '1330919816'); INSERT INTO `article` VALUES ('166', '使用jQuery实现跨域提交表单数据', '1331386130'); INSERT INTO `article` VALUES ('167', '浅谈响应式WEB设计', '1333072250'); INSERT INTO `article` VALUES ('168', '日期选择器:jquery datepicker的使用', '1333890332'); INSERT INTO `article` VALUES ('169', '日期时间选择器:datetimepicker', '1334306433'); INSERT INTO `article` VALUES ('170', '性能优化:如何更快速加载你的JS页面', '1335099220'); INSERT INTO `article` VALUES ('171', '使用PHP导入和导出CSV文件', '1335949304'); INSERT INTO `article` VALUES ('172', '使用PHP导入Excel和导出数据为Excel文件', '1336833793'); INSERT INTO `article` VALUES ('173', '使用PHP生成和获取XML格式数据', '1337485842'); INSERT INTO `article` VALUES ('174', 'HTML5教程和参考手册分享', '1337868595'); INSERT INTO `article` VALUES ('175', 'jQuery实现多级手风琴菜单', '1337952939'); INSERT INTO `article` VALUES ('176', '响应式WEB设计:将导航菜单转换成下拉菜单以适应小屏幕设备', '1338529515'); INSERT INTO `article` VALUES ('177', '使用HTML5的Audio标签打造WEB音频播放器', '1339598461'); INSERT INTO `article` VALUES ('178', 'Javascript+PHP实现在线拍照功能', '1340860377'); INSERT INTO `article` VALUES ('179', 'jQuery+PHP+Mysql在线拍照和在线浏览照片', '1341836937'); INSERT INTO `article` VALUES ('180', 'HTML5视频标签video', '1342165895'); INSERT INTO `article` VALUES ('181', '页面前端的水有多深?', '1342239180'); INSERT INTO `article` VALUES ('182', 'jQuery倒计时', '1342938362'); INSERT INTO `article` VALUES ('183', '使用jQuery+PHP+Mysql实现抽奖程序', '1343566149'); INSERT INTO `article` VALUES ('184', 'PHP+jQuery实现翻板抽奖', '1344063552'); INSERT INTO `article` VALUES ('185', 'HTML5之画布Canvas', '1345122224'); INSERT INTO `article` VALUES ('186', 'PHP+jQuery+Ajax+Mysql实现发表心情功能', '1345615563'); INSERT INTO `article` VALUES ('188', '基于jQuery+JSON的省市联动效果', '1347458264'); INSERT INTO `article` VALUES ('189', 'jQuery+php实现ajax文件即时上传', '1348398783'); INSERT INTO `article` VALUES ('190', '根据IP定位用户所在城市信息', '1348663533'); INSERT INTO `article` VALUES ('191', 'PHP生成各种验证码和Ajax验证', '1349525471'); INSERT INTO `article` VALUES ('192', 'HTML5应用之文件拖拽上传', '1350480671'); INSERT INTO `article` VALUES ('193', '一款基于jQuery的颜色拾取器', '1351523466'); INSERT INTO `article` VALUES ('194', 'jQuery实现页面滚动时元素智能定位', '1351688409'); INSERT INTO `article` VALUES ('195', 'jQuery+Ajax+PHP+Mysql实现分页显示数据', '1352125590'); INSERT INTO `article` VALUES ('196', 'jQuery实现返回顶部按钮效果', '1353217028'); INSERT INTO `article` VALUES ('197', 'jQuery+Ajax+PHP实现“喜欢”评级功能', '1353590248'); INSERT INTO `article` VALUES ('198', '使用jQuery和CSS将背景图片拉伸', '1353940570'); INSERT INTO `article` VALUES ('199', 'timeago.js自动将时间戳转换为更易读的时间轴', '1355158678'); INSERT INTO `article` VALUES ('200', 'HTML5+CSS3打造可自动获得焦点和支持语音输入的超酷搜索框', '1355400595'); INSERT INTO `article` VALUES ('201', 'HTML5本地存储', '1355925764'); INSERT INTO `article` VALUES ('202', '分享一款基于jQuery的QQ表情插件', '1356527449'); INSERT INTO `article` VALUES ('203', 'Javascript与HTML5的canvas实现图片旋转效果', '1357737224'); INSERT INTO `article` VALUES ('204', 'PHP递归实现无限级分类', '1358252514'); INSERT INTO `article` VALUES ('205', '使用PHPMailer发送带附件并支持HTML内容的邮件', '1359461653'); INSERT INTO `article` VALUES ('206', 'PHP+Mysql+jQuery统计当前在线用户数', '1360999500'); INSERT INTO `article` VALUES ('207', 'jQuery实现等比例缩放大图片', '1362236073'); INSERT INTO `article` VALUES ('208', '速度超快的菜单切换效果', '1363182955'); INSERT INTO `article` VALUES ('209', '使用Ctrl+Enter提交表单', '1363615171'); INSERT INTO `article` VALUES ('210', '使用PHP采集远程图片', '1363960502'); INSERT INTO `article` VALUES ('211', 'jQuery时间轴插件:jQuery Timelinr', '1364393950'); INSERT INTO `article` VALUES ('212', 'jQuery Easing 动画效果扩展', '1365428407'); INSERT INTO `article` VALUES ('213', '超酷的固定菜单页面滚动效果', '1365921498'); INSERT INTO `article` VALUES ('214', 'PHP+Mysql+jQuery实现文件下载次数统计', '1366639853'); INSERT INTO `article` VALUES ('215', '幸运大转盘-jQuery+PHP实现的抽奖程序(上)', '1367244989'); INSERT INTO `article` VALUES ('216', '幸运大转盘-jQuery+PHP实现的抽奖程序(下)', '1367501196'); INSERT INTO `article` VALUES ('217', 'jQuery数字滚动展示效果', '1368538200'); INSERT INTO `article` VALUES ('218', '砸金蛋:jQuery+PHP实现的砸金蛋中奖程序', '1369406421'); INSERT INTO `article` VALUES ('219', '响应式内容滑动插件bxSlider', '1370350238'); INSERT INTO `article` VALUES ('220', 'jQuery+HTML5声音提示', '1371218736'); INSERT INTO `article` VALUES ('221', 'WEB开发中常用的正则表达式', '1371558930'); INSERT INTO `article` VALUES ('222', 'Zclip:复制页面内容到剪贴板兼容各浏览器', '1372769186'); INSERT INTO `article` VALUES ('223', 'jQuery实现的向下推送图文信息滚动效果', '1373034355'); INSERT INTO `article` VALUES ('224', 'FileReader:读取本地图片文件并显示', '1374496739'); INSERT INTO `article` VALUES ('225', 'iPictrue:图片标注提示', '1375624096'); INSERT INTO `article` VALUES ('226', '使用jquery.qrcode生成二维码', '1375970580'); INSERT INTO `article` VALUES ('227', 'PHP汉字拼音转换和公历农历转换', '1376716887'); INSERT INTO `article` VALUES ('228', 'PHP用户注册邮箱验证激活帐号', '1377694338'); INSERT INTO `article` VALUES ('229', 'PHP+Mysql+jQuery找回密码', '1377694339'); INSERT INTO `article` VALUES ('230', '关于pagination的使用', '1323424234');
true
439c4fdcbbfbbfda56012d834f4f2c8c69e3056e
SQL
spajdz/appclay
/scripts/sql10239032.sql
UTF-8
2,959
3.65625
4
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.7.1 -- https://www.phpmyadmin.net/ -- -- Host: sql10.freesqldatabase.com -- Generation Time: May 20, 2018 at 08:42 PM -- Server version: 5.5.58-0ubuntu0.14.04.1 -- PHP Version: 7.0.30-0ubuntu0.16.04.1 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: `sql10239032` -- DELIMITER $$ -- -- Procedures -- CREATE DEFINER=`sql10239032`@`%` PROCEDURE `sp_insertRecord` (IN `m_fecha` DATE, IN `m_oficina` VARCHAR(45), IN `m_descripcion` TEXT, IN `m_nro_documento` VARCHAR(45), IN `m_cargo` BIGINT, IN `m_abono` BIGINT, IN `m_saldo` BIGINT) NO SQL BEGIN DECLARE id_movimiento_count BIGINT DEFAULT 0; DECLARE movimiento_count INT DEFAULT 0; DECLARE fecha_buscar DATE; IF DAYOFWEEK(m_fecha) = 2 THEN SET fecha_buscar = DATE_SUB(m_fecha, INTERVAL 3 DAY); ELSE SET fecha_buscar = DATE_SUB(m_fecha, INTERVAL 1 DAY); END IF; SELECT id,COUNT(id) INTO id_movimiento_count, movimiento_count FROM cartola c WHERE ( c.fecha = fecha_buscar OR c.fecha = m_fecha ) AND c.oficina = m_oficina AND c.descripcion = m_descripcion AND c.nro_documento = m_nro_documento AND c.cargo = m_cargo AND c.abono = m_abono LIMIT 1; IF movimiento_count = 0 THEN -- Si no hay lo creo INSERT INTO cartola VALUES( NULL , m_fecha , m_oficina , m_descripcion , m_nro_documento , m_cargo , m_abono , m_saldo ); ELSE -- Si existe se hace update del dia UPDATE cartola SET fecha = m_fecha, saldo = m_saldo WHERE id = id_movimiento_count; END IF; END$$ DELIMITER ; -- -------------------------------------------------------- -- -- Table structure for table `cartola` -- CREATE TABLE `cartola` ( `id` bigint(20) NOT NULL, `fecha` date DEFAULT NULL, `oficina` varchar(45) DEFAULT NULL, `descripcion` text, `nro_documento` varchar(45) DEFAULT NULL, `cargo` bigint(20) DEFAULT NULL, `abono` bigint(20) DEFAULT NULL, `saldo` bigint(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Indexes for dumped tables -- -- -- Indexes for table `cartola` -- ALTER TABLE `cartola` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `cartola` -- ALTER TABLE `cartola` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=113;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
84463f4166f812dd765650661cb9695c6b099d3f
SQL
GiGaByTee/springMVC
/src/main/resources/schema.sql
UTF-8
345
2.515625
3
[]
no_license
CREATE TABLE user ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY , username VARCHAR(20) NOT NULL , email VARCHAR NOT NULL, password VARCHAR NOT NULL , create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP); INSERT INTO User(username, email, password) VALUES ('Cardinal', 'Stavanger', 'Norway'), ('Taras', 'Shev4enko', 'Ukraine');
true
f1d10a4b74e981c0cb54404915ae1461d80e4834
SQL
k4cruise23/helo
/db/seed.sql
UTF-8
238
2.765625
3
[]
no_license
CREATE TABLE posts ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), title TEXT, imageURL TEXT, content TEXT ); CREATE TABLE users ( id SERIAL PRIMARY KEY, username TEXT, profileImage TEXT, password TEXT );
true
26968762bc4a07f32a08d2a09712e3fcaeedb592
SQL
yourunSpb/card-call-ambulance
/cca-database/deploy_database.sql
UTF-8
10,649
3.515625
4
[]
no_license
/*==============================================================*/ /* CREATE SEQUENCE */ /*==============================================================*/ create sequence SEQ_ANSWER_ID increment by 1 start with 1; create sequence SEQ_BRIGADE_ID increment by 1 start with 1; create sequence SEQ_CARD_ID increment by 1 start with 1; create sequence SEQ_DEP_ID increment by 1 start with 1; create sequence SEQ_LOOKUP_ID increment by 1 start with 1; create sequence SEQ_MEDIC_ID increment by 1 start with 1; create sequence SEQ_POSITION_ID increment by 1 start with 1; create sequence SEQ_PROFILE_ID increment by 1 start with 1; create sequence SEQ_QUESTION_ID increment by 1 start with 1; create sequence SEQ_ROLE_ID increment by 1 start with 1; create sequence SEQ_SECTION_ID increment by 1 start with 1; create sequence SEQ_USER_ID increment by 1 start with 1; /*==============================================================*/ /* Table: ANSWER */ /*==============================================================*/ create table ANSWER ( ANSWER_ID NUMBER not null, QUESTION_ID NUMBER, ANSWER_VALUE VARCHAR2(255) ); alter table ANSWER add constraint PK_ANSWER primary key (ANSWER_ID); /*==============================================================*/ /* Table: BRIGADE */ /*==============================================================*/ create table BRIGADE ( BRIGADE_ID NUMBER not null, BRIGADE_NUMBER NUMBER, DEPARTMENT_ID NUMBER, PROFILE_ID NUMBER ); alter table BRIGADE add constraint PK_BRIGADE primary key (BRIGADE_ID); /*==============================================================*/ /* Table: BRIGADE_PROFILE */ /*==============================================================*/ create table BRIGADE_PROFILE ( PROFILE_ID NUMBER not null, REDUCTION VARCHAR2(7), TRANSCRIPT VARCHAR2(100) ); alter table BRIGADE_PROFILE add constraint PK_BRIGADE_PROFILE primary key (PROFILE_ID); /*==============================================================*/ /* Table: CARD_CALL */ /*==============================================================*/ create table CARD_CALL ( CARD_CALL_ID number not null, CREATE_DATE_TIME DATE, STATUS VARCHAR2(20), UPDATED_BY NUMBER, UPDATE_DATE_TIME DATE, CARD_CALL_CONTENT BLOB, BRIGADE_ID NUMBER ); alter table CARD_CALL add constraint PK_CARD_CALL primary key (CARD_CALL_ID); /*==============================================================*/ /* Table: COMPOSITION */ /*==============================================================*/ create table COMPOSITION ( MEDIC_ID NUMBER not null, BRIGADE_ID NUMBER not null ); alter table COMPOSITION add constraint PK_COMPOSITION primary key (MEDIC_ID, BRIGADE_ID); /*==============================================================*/ /* Index: COMPOSITION_MEDIC_ID */ /*==============================================================*/ create index COMPOSITION_MEDIC_ID on COMPOSITION ( MEDIC_ID ASC ); /*==============================================================*/ /* Index: COMPOSITION_BRIGADE_ID */ /*==============================================================*/ create index COMPOSITION_BRIGADE_ID on COMPOSITION ( BRIGADE_ID ASC ); /*==============================================================*/ /* Table: DEPARTMENT */ /*==============================================================*/ create table DEPARTMENT ( DEPARTMENT_ID NUMBER not null, DEPARTMENT_NAME VARCHAR2(150) ); alter table DEPARTMENT add constraint PK_DEPARTMENT primary key (DEPARTMENT_ID); /*==============================================================*/ /* Table: LOOKUP_SECTION */ /*==============================================================*/ create table LOOKUP_SECTION ( LOOKUP_ID NUMBER not null, CARD_CALL_ID NUMBER not null, QUESTION_ID NUMBER, ANSWER_ID NUMBER, ANSWER_VALUE VARCHAR2(1000) ); alter table LOOKUP_SECTION add constraint PK_LOOKUP_SECTION primary key (LOOKUP_ID); /*==============================================================*/ /* Index: LOOKUP_CARD_CALL_ID */ /*==============================================================*/ create index LOOKUP_CARD_CALL_ID on LOOKUP_SECTION ( CARD_CALL_ID ASC ); /*==============================================================*/ /* Table: MEDIC */ /*==============================================================*/ create table MEDIC ( MEDIC_ID NUMBER not null, POSITION_ID NUMBER, USER_ID NUMBER ); alter table MEDIC add constraint PK_MEDIC primary key (MEDIC_ID); /*==============================================================*/ /* Table: MEDIC_POSITION */ /*==============================================================*/ create table MEDIC_POSITION ( POSITION_ID NUMBER not null, POSITION_VALUE VARCHAR2(100) ); alter table MEDIC_POSITION add constraint PK_MEDIC_POSITION primary key (POSITION_ID); /*==============================================================*/ /* Table: MEDIC_ROLE */ /*==============================================================*/ create table MEDIC_ROLE ( MEDIC_ID NUMBER not null, ROLE_ID NUMBER not null ); alter table MEDIC_ROLE add constraint PK_MEDIC_ROLE primary key (MEDIC_ID, ROLE_ID); /*==============================================================*/ /* Index: USER_MEDIC_ID */ /*==============================================================*/ create index USER_MEDIC_ID on MEDIC_ROLE ( MEDIC_ID ASC ); --/*==============================================================*/ --/* Index: USER_ROLE_ID */ --/*==============================================================*/ --create index USER_ROLE_ID on MEDIC_ROLE ( -- ROLE_ID ASC --); /*==============================================================*/ /* Table: MEDIC_USER */ /*==============================================================*/ create table MEDIC_USER ( USER_ID NUMBER not null, FIRST_NAME VARCHAR2(50), MIDDLE_NAME VARCHAR2(50), LAST_NAME VARCHAR2(50), E_MAIL_ADDRESS VARCHAR2(50) ); alter table MEDIC_USER add constraint PK_MEDIC_USER primary key (USER_ID); /*==============================================================*/ /* Table: QUESTION */ /*==============================================================*/ create table QUESTION ( QUESTION_ID NUMBER not null, SECTION_ID NUMBER not null, QUESTION_ORDER NUMBER, QUESTION_TEXT VARCHAR2(255), ANSWER_TYPE VARCHAR2(20) ); alter table QUESTION add constraint PK_QUESTION primary key (QUESTION_ID); /*==============================================================*/ /* Table: SECTION */ /*==============================================================*/ create table SECTION ( SECTION_ID NUMBER not null, SECTION_NAME VARCHAR2(255) not null, SECTION_DESCRIPTION VARCHAR2(255) ); alter table SECTION add constraint PK_SECTION primary key (SECTION_ID); /*==============================================================*/ /* Table: USER_ROLE */ /*==============================================================*/ create table USER_ROLE ( ROLE_ID NUMBER not null, ROLE_VALUE VARCHAR2(50) ); alter table USER_ROLE add constraint PK_USER_ROLE primary key (ROLE_ID); alter table ANSWER add constraint FK_ANSWER_QUESTION foreign key (QUESTION_ID) references QUESTION (QUESTION_ID); alter table BRIGADE add constraint FK_BRIGADE_PROFILE foreign key (PROFILE_ID) references BRIGADE_PROFILE (PROFILE_ID); alter table BRIGADE add constraint FK_BRIGADE_DEPARTMET foreign key (DEPARTMENT_ID) references DEPARTMENT (DEPARTMENT_ID); alter table CARD_CALL add constraint FK_CARD_CALL_BRIGADE foreign key (BRIGADE_ID) references BRIGADE (BRIGADE_ID); alter table CARD_CALL add constraint FK_CARD_CAL_REFERENCE_MEDIC foreign key (UPDATED_BY) references MEDIC (MEDIC_ID); alter table COMPOSITION add constraint FK_COMPOSIT_BRIGADE foreign key (BRIGADE_ID) references BRIGADE (BRIGADE_ID); alter table COMPOSITION add constraint FK_COMPOSIT_REFERENCE_MEDIC foreign key (MEDIC_ID) references MEDIC (MEDIC_ID); alter table LOOKUP_SECTION add constraint FK_LOOKUP_CARD_CALL foreign key (CARD_CALL_ID) references CARD_CALL (CARD_CALL_ID); -- --alter table LOOKUP_SECTION -- add constraint FK_LOOKUP_QUESTION foreign key (QUESTION_ID) -- references QUESTION (QUESTION_ID); --alter table LOOKUP_SECTION -- add constraint FK_LOOKUP_S_REFERENCE_ANSWER foreign key (ANSWER_ID) -- references ANSWER (ANSWER_ID); alter table MEDIC add constraint FK_MEDIC_POSITION foreign key (POSITION_ID) references MEDIC_POSITION (POSITION_ID); alter table MEDIC add constraint FK_MEDIC_USER foreign key (USER_ID) references MEDIC_USER (USER_ID); alter table MEDIC_ROLE add constraint FK_MEDIC_ROLE foreign key (MEDIC_ID) references MEDIC (MEDIC_ID); alter table MEDIC_ROLE add constraint FK_ROLE_MEDIC foreign key (ROLE_ID) references USER_ROLE (ROLE_ID); alter table QUESTION add constraint FK_QUESTION_SECTION foreign key (SECTION_ID) references SECTION (SECTION_ID); COMMIT;
true
eeb431201429f4c6a792e2d01ccba30a8643b1fe
SQL
BankruptJere/Finale
/stockbarang.sql
UTF-8
2,966
3.1875
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 5.0.4 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: May 31, 2021 at 06:51 PM -- Server version: 10.4.16-MariaDB -- PHP Version: 7.3.24 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: `stockbarang` -- -- -------------------------------------------------------- -- -- Table structure for table `keluar` -- CREATE TABLE `keluar` ( `id_keluar` int(11) NOT NULL, `id_barang` int(11) NOT NULL, `tanggal` timestamp NOT NULL DEFAULT current_timestamp(), `penerima` varchar(25) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `login` -- CREATE TABLE `login` ( `id_user` int(11) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `phone_number` varchar(20) NOT NULL, `type` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `login` -- INSERT INTO `login` (`id_user`, `email`, `password`, `phone_number`, `type`) VALUES (1, 'test@gmail.com', 'jeremiah17', '123456789', 'Admin'); -- -------------------------------------------------------- -- -- Table structure for table `masuk` -- CREATE TABLE `masuk` ( `id_masuk` int(11) NOT NULL, `id_barang` int(11) NOT NULL, `tanggal` timestamp NOT NULL DEFAULT current_timestamp(), `keterangan` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `stock` -- CREATE TABLE `stock` ( `id_barang` int(11) NOT NULL, `kategori` varchar(50) NOT NULL, `nama_barang` varchar(50) NOT NULL, `harga` int(20) NOT NULL, `jumlah` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Indexes for dumped tables -- -- -- Indexes for table `login` -- ALTER TABLE `login` ADD PRIMARY KEY (`id_user`); -- -- Indexes for table `masuk` -- ALTER TABLE `masuk` ADD PRIMARY KEY (`id_masuk`); -- -- Indexes for table `stock` -- ALTER TABLE `stock` ADD PRIMARY KEY (`id_barang`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `login` -- ALTER TABLE `login` MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `masuk` -- ALTER TABLE `masuk` MODIFY `id_masuk` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `stock` -- ALTER TABLE `stock` MODIFY `id_barang` int(11) NOT NULL AUTO_INCREMENT; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
fed28b5575804f9fa2893b2c91842b5be4409e1d
SQL
ldvalle/Rdd_Storeds
/sp_rdd_get_documento.sql
WINDOWS-1252
5,442
3.171875
3
[]
no_license
DROP PROCEDURE rdd_get_documento; CREATE PROCEDURE rdd_get_documento(valor_busqueda char(46)) RETURNING char(3) as codigo, char(100) as descri, float as monto, char(12) as nro_documento, char(10) as fecha_emision, char(10) as fecha_vcto; DEFINE ret_monto_deuda float; DEFINE ret_nro_documento char(12); DEFINE ret_fecha_emision char(10); DEFINE ret_fecha_vencimiento char(10); DEFINE empresa_barra char(3); DEFINE sucursal_barra char(2); DEFINE plan_barra char(2); DEFINE nro_cliente_barra char(8); DEFINE importe_barra char(9); DEFINE vcto1_barra char(6); DEFINE recargo_barra char(6); DEFINE vcto2_barra char(4); DEFINE corr_factu_barra char(3); DEFINE tipo_mov_barra char(2); DEFINE dv_barra char(1); DEFINE nro_cliente integer; DEFINE dFechaVcto1 date; DEFINE dFechaVcto2 date; DEFINE sFechaVcto2 char(6); DEFINE fMonto float; DEFINE fRecargo float; DEFINE dFecha_actual date; DEFINE dFecha_emision date; DEFINE icorrelativo int; DEFINE nrows int; DEFINE ndias int; DEFINE sNroDocumento char(12); SET ISOLATION TO DIRTY READ; LET empresa_barra=valor_busqueda[1,3]; LET sucursal_barra=valor_busqueda[4,5]; LET plan_barra=valor_busqueda[6,7]; LET nro_cliente_barra=valor_busqueda[8,15]; LET importe_barra=valor_busqueda[16,24]; LET vcto1_barra=valor_busqueda[25,30]; LET recargo_barra=valor_busqueda[31,36]; LET vcto2_barra=valor_busqueda[37,40]; LET corr_factu_barra=valor_busqueda[41,43]; LET tipo_mov_barra=valor_busqueda[44,45]; LET dv_barra=valor_busqueda[46,46]; LET nro_cliente = TO_NUMBER(nro_cliente_barra); LET dFechaVcto1=TO_DATE(vcto1_barra, '%y%m%d'); IF vcto2_barra != '0000' THEN LET sFechaVcto2=valor_busqueda[25,26] || valor_busqueda[37,40]; LET dFechaVcto2=TO_DATE(sFechaVcto2, '%y%m%d'); ELSE LET dFechaVcto2=dFechaVcto1; END IF; LET fMonto = (TO_NUMBER(importe_barra)/100); LET fRecargo = (TO_NUMBER(recargo_barra)/100); LET icorrelativo=TO_NUMBER(corr_factu_barra); SELECT TODAY INTO dFecha_actual FROM dual; IF tipo_mov_barra = '05' THEN -- Pago anticipo Convenio SELECT fecha_creacion, fecha_vto_1 INTO dFecha_emision, dFechaVcto1 FROM conve WHERE numero_cliente = nro_cliente AND nro_docto = icorrelativo AND estado = 'S'; LET nrows = DBINFO('sqlca.sqlerrd2'); IF nrows=0 THEN RETURN '110', 'Cliente no tiene convenio solicitado', 0, '', '', ''; END IF; LET ret_monto_deuda=fMonto; LET ret_nro_documento= lpad(nro_cliente,8, '0') || lpad(icorrelativo, 4, '0'); LET ret_fecha_emision=to_char(dFecha_emision, '%d/%m/%Y'); LET ret_fecha_vencimiento=to_char(dFechaVcto1, '%d/%m/%Y'); ELIF tipo_mov_barra = '06' OR tipo_mov_barra = '96' THEN -- Factura energia SELECT fecha_facturacion, fecha_vencimiento1, fecha_vencimiento2, centro_emisor || tipo_docto || lpad(numero_factura, 8, '0') INTO dFecha_emision, dFechaVcto1, dFechaVcto2, sNroDocumento FROM hisfac WHERE numero_cliente = nro_cliente AND corr_facturacion = icorrelativo; LET nrows = DBINFO('sqlca.sqlerrd2'); IF nrows=0 THEN RETURN '111', 'No se encuentra factura asociada a la barra.', 0, '', '', ''; END IF; LET ret_fecha_emision=to_char(dFecha_emision, '%d/%m/%Y'); LET ret_nro_documento= sNroDocumento; IF dFechaVcto1 < dFecha_actual THEN LET ret_monto_deuda=fMonto + fRecargo; LET ret_fecha_vencimiento=to_char(dFechaVcto2, '%d/%m/%Y'); ELSE LET ret_monto_deuda=fMonto; LET ret_fecha_vencimiento=to_char(dFechaVcto1, '%d/%m/%Y'); END IF; ELIF tipo_mov_barra = '10' OR tipo_mov_barra = '45' THEN -- pvd pcp SELECT round(valor,0) INTO ndias FROM tabla WHERE sucursal = '0000' AND nomtabla = 'COMPAG' AND codigo = 'EXTERN' AND fecha_activacion <= TODAY AND (fecha_desactivac > TODAY OR fecha_desactivac IS NULL); LET nrows = DBINFO('sqlca.sqlerrd2'); IF nrows=0 THEN LET ndias=0; END IF; SELECT lpad(l1.numero_cliente, 8, '0') || lpad(l1.nro_comprob, 4, '0'), l1.fecha_emision INTO sNroDocumento, dFecha_emision FROM log_comprob l1 WHERE l1.numero_cliente = nro_cliente AND l1.tipo_comprob = tipo_mov_barra AND l1.nro_comprob = icorrelativo AND l1.monto_comprob = fMonto AND l1.fecha_anulacion IS NULL AND l1.fecha_pago IS NULL AND l1.fecha_emision = (SELECT MAX(l2.fecha_emision) FROM log_comprob l2 WHERE l2.numero_cliente = l1.numero_cliente AND l2.tipo_comprob = tipo_mov_barra AND l2.nro_comprob = l1.nro_comprob AND l2.monto_comprob = l1.monto_comprob AND l2.fecha_anulacion IS NULL AND l2.fecha_pago IS NULL AND l2.fecha_emision BETWEEN (TODAY - ndias) AND TODAY); LET nrows = DBINFO('sqlca.sqlerrd2'); IF nrows=0 THEN RETURN '112', 'No se encuentra documento asociado a la barra.', 0, '', '', ''; END IF; LET ret_monto_deuda=fMonto; LET ret_nro_documento= sNroDocumento; LET ret_fecha_emision=to_char(dFecha_emision, '%d/%m/%Y'); LET ret_fecha_vencimiento=to_char(dFechaVcto1, '%d/%m/%Y'); ELSE RETURN '105', 'Tipo de barra invalida', 0, '', '', ''; END IF; RETURN '0', 'OK', ret_monto_deuda, ret_nro_documento, ret_fecha_emision, ret_fecha_vencimiento; END PROCEDURE; GRANT EXECUTE ON rdd_get_documento TO superpjp, supersre, supersbl, supersc, corbacho, guardt1, fuse, ctousu, batchsyn, procbatc, "UCENTRO", "OVIRTUAL", pjp, sreyes, sbl, ssalve, gtricoci, pablop, aarrien, vdiaz, ldvalle, vaz;
true
191b2270a752fbafe3a062381c86e36e23e8a073
SQL
Sarius997/ReiseFieber
/ImportantSqlStatements/create_table_kunden.sql
UTF-8
522
2.875
3
[]
no_license
-- Table: kunden -- DROP TABLE kunden; CREATE TABLE kunden ( id integer NOT NULL DEFAULT nextval('kdid'::regclass), nachname character varying(128), vorname character varying(128), wohnort character varying(128), geburtstag character varying(128), volljaehrig character varying(128), telefonnummer character varying(128), geschlecht character varying(128), postleitzahl text, adresse text, CONSTRAINT kunden_pkey PRIMARY KEY (id) ) WITH ( OIDS=FALSE ); ALTER TABLE kunden OWNER TO postgres;
true
50deb8bbb4ab8de24093f3744f3027b7e62b48bd
SQL
shagstone/yesimo_work_repo
/supplier_catalog/Tables/suppl_x12.sql
UTF-8
1,976
3.515625
4
[]
no_license
-- ----------------------------------------------------- -- Table suppl_x12 -- ----------------------------------------------------- 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'; CREATE SCHEMA IF NOT EXISTS supplier_catalog DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; SHOW WARNINGS; USE supplier_catalog; DROP TABLE IF EXISTS suppl_x12 ; CREATE TABLE IF NOT EXISTS suppl_x12 ( suppl_x12_sid MEDIUMINT NOT NULL AUTO_INCREMENT, suppl_x12_id MEDIUMINT NOT NULL , trans_type_id SMALLINT NOT NULL, supplier_id SMALLINT NOT NULL, suppl_x12_grp_code MEDIUMINT, parent_suppl_x12_grp_code VARCHAR(100), suppl_x12_grp_name VARCHAR(100), suppl_x12_grp_desc VARCHAR(500), suppl_x12_name VARCHAR(100) NOT NULL, suppl_x12_value VARCHAR(10), from_date DATE NOT NULL, to_date DATE, display_name VARCHAR(500 ) NOT NULL, oprtnl_flag CHAR(1 ) DEFAULT 'A' NOT NULL, create_date DATETIME NOT NULL COMMENT 'Record creation date.' , create_by VARCHAR(50) NULL COMMENT 'Record created by.' , update_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Record modfication date.', update_by VARCHAR(50) NULL COMMENT 'Record updated by.' , PRIMARY KEY(suppl_x12_sid) -- , UNIQUE KEY (suppl_x12_id, trans_type_id,suppl_x12_grp_code, suppl_x12_grp_desc, suppl_x12_value, from_date) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8, COMMENT = 'Supplier Address Table'; SHOW WARNINGS; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
true
1891bd07b71b52aac36ffc5032abf2223fa6c475
SQL
asanchezaguirre/sql-capstone-project
/sprint_3.sql
UTF-8
645
4.1875
4
[]
no_license
/*Show all students ordered by last name in ascendent way.*/ SELECT * FROM Student ORDER BY lastName DESC; /*Write a query to list all the students living in the Whitman dorm.*/ SELECT * FROM Student WHERE dormName="Whitman"; /*Write a query to list the number of students assigned to each faculty advisor.*/ SELECT COUNT(studentID) FROM Advisor_Student_Date GROUP BY advisorID; /*Write a query to list first name, last name, and email, and company name of the alumni working as a mentor in the university.*/ SELECT M.firstName, M.lastName, M.mentorEmail, C.companyName FROM Mentor M INNER JOIN Company C ON C.companyPhone= M.companyPhone;
true
290b4a6b2aa54b681ca11977c2d2246770722214
SQL
yunling0115/DBXML
/SQL/q7.sql
UTF-8
258
3.09375
3
[]
no_license
-- 'C:\Users\yling\workspace\Hw1\META-INF\q7.sql' -- Find users who have not posted any tweets, and output their user ids and full names select u.userid, u.fullname from Users u, Tweets t where u.userid=t.userid group by u.userid having count(t.tweetid)=0;
true
df0fd1493fd79b07036db3633e6a8b6ba8e9d2a6
SQL
jkstill/oracle-script-lib
/sql/getstat.sql
UTF-8
499
2.578125
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
set echo off verify off pause off feed on col stat new_value statname noprint prompt Enter Statname ( Partial OK ): set feed off term off select '&&1' stat from dual; set feed on term on @@ttitle 'V$SYSSTAT for &&statname' ttitle on clear col clear break break on class col name format a40 col value format 9999,999,999,999 col class format 9999 select class,name, value from v$sysstat where name like '%&&statname%' order by class,name / prompt prompt prompt ttitle off undef 1
true
e264e8c3acbc5066b9f12e8c335250babd89494f
SQL
8moustapha8/website
/database/1.1/base/2_tables/payment_type.sql
UTF-8
1,250
3.5
4
[]
no_license
use moneyiq; SET NAMES utf8; -- Table payment_type -- required as we want to be able to refresh our db table by table SET FOREIGN_KEY_CHECKS = 0; -- turn off note warnings as tables don't exist during initial load SET sql_notes = 0; DROP TABLE IF EXISTS `payment_type`; DROP TABLE IF EXISTS `payment_type_history`; SET sql_notes = 1; CREATE TABLE payment_type ( payment_type_id int NOT NULL AUTO_INCREMENT, payment_type varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, payment_description text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, update_time datetime NOT NULL, update_user varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, CONSTRAINT payment_type_pk PRIMARY KEY (payment_type_id) ); CREATE TABLE payment_type_history ( payment_type_id int NOT NULL , payment_type varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, payment_description text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, time_beg datetime NOT NULL, time_end datetime NULL, update_user varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, CONSTRAINT payment_type_pk PRIMARY KEY (payment_type_id, time_beg) ); SET FOREIGN_KEY_CHECKS = 1;
true
d95697f0e1cc53894c6cfef374e549ef83cb2c98
SQL
radtek/abs3
/sql/mmfo/bars/Table/skr_import_safes.sql
UTF-8
3,090
3.265625
3
[]
no_license
PROMPT ===================================================================================== PROMPT *** Run *** ========== Scripts /Sql/BARS/Table/SKR_IMPORT_SAFES.sql =========*** Run PROMPT ===================================================================================== PROMPT *** ALTER_POLICY_INFO to SKR_IMPORT_SAFES *** BEGIN execute immediate 'begin bpa.alter_policy_info(''SKR_IMPORT_SAFES'', ''CENTER'' , null, null, null, null); bpa.alter_policy_info(''SKR_IMPORT_SAFES'', ''FILIAL'' , null, null, null, null); bpa.alter_policy_info(''SKR_IMPORT_SAFES'', ''WHOLE'' , null, null, null, null); null; end; '; END; / PROMPT *** Create table SKR_IMPORT_SAFES *** begin execute immediate ' CREATE TABLE BARS.SKR_IMPORT_SAFES ( SNUM VARCHAR2(64 CHAR), O_SK NUMBER, BRANCH VARCHAR2(30) DEFAULT sys_context(''bars_context'',''user_branch''), ERROR VARCHAR2(1024 CHAR), IMPORTED NUMBER(1,0) DEFAULT 0 ) SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING TABLESPACE BRSDYND '; exception when others then if sqlcode=-955 then null; else raise; end if; end; / PROMPT *** ALTER_POLICIES to SKR_IMPORT_SAFES *** exec bpa.alter_policies('SKR_IMPORT_SAFES'); COMMENT ON TABLE BARS.SKR_IMPORT_SAFES IS ''; COMMENT ON COLUMN BARS.SKR_IMPORT_SAFES.SNUM IS ''; COMMENT ON COLUMN BARS.SKR_IMPORT_SAFES.O_SK IS ''; COMMENT ON COLUMN BARS.SKR_IMPORT_SAFES.BRANCH IS ''; COMMENT ON COLUMN BARS.SKR_IMPORT_SAFES.ERROR IS ''; COMMENT ON COLUMN BARS.SKR_IMPORT_SAFES.IMPORTED IS ''; PROMPT *** Create constraint PK_SKRIMPORTSAFES *** begin execute immediate ' ALTER TABLE BARS.SKR_IMPORT_SAFES ADD CONSTRAINT PK_SKRIMPORTSAFES PRIMARY KEY (SNUM, BRANCH) USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS TABLESPACE BRSDYND ENABLE NOVALIDATE'; exception when others then if sqlcode=-2260 or sqlcode=-2261 or sqlcode=-2264 or sqlcode=-2275 or sqlcode=-1442 then null; else raise; end if; end; / PROMPT *** Create index PK_SKRIMPORTSAFES *** begin execute immediate ' CREATE UNIQUE INDEX BARS.PK_SKRIMPORTSAFES ON BARS.SKR_IMPORT_SAFES (SNUM, BRANCH) PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS TABLESPACE BRSDYND '; exception when others then if sqlcode=-955 then null; else raise; end if; end; / PROMPT *** Create grants SKR_IMPORT_SAFES *** grant SELECT on SKR_IMPORT_SAFES to BARSREADER_ROLE; grant SELECT on SKR_IMPORT_SAFES to UPLD; PROMPT ===================================================================================== PROMPT *** End *** ========== Scripts /Sql/BARS/Table/SKR_IMPORT_SAFES.sql =========*** End PROMPT =====================================================================================
true
4ab8cd340a773c37055aa37756550e2b5f843950
SQL
ProfDema/uam
/pam/examples/anon_data/group_0093/q2.sql
UTF-8
241
2.71875
3
[]
no_license
truncate query2; INSERT INTO Query2( SELECT oid, pid, wid, ordqty, stockqty FROM orders, stock WHERE stock.status = 'O', stock.wid = orders.shipwid , stock.pid = orders.pid , stock.quantity<orders.quantity ) select * from query2;
true
ff73927cabfefcfffaf7135e937ffe0f659b55e7
SQL
PeterMcHoke/youchef-api
/migrations/001.do.create_savedrecipes.sql
UTF-8
216
3.3125
3
[]
no_license
CREATE TABLE saved_recipes ( user_id INT NOT NULL, recipe_id INT NOT NULL, date_viewed TIMESTAMP DEFAULT now() NOT NULL UNIQUE (user_id, recipe_id), FOREIGN KEY (user_id) REFERENCES users (id) );
true
697cb3e884de3af3f8a81a2bb3ff7e581adb5097
SQL
locmark/bazy_projekt
/sample_data.sql
UTF-8
2,405
2.90625
3
[]
no_license
INSERT INTO Akademiki(nazwa, adres) VALUES ('DS1', 'Traugutta 115, Gdansk-Wrzeszcz 80-226'), ('DS2', 'Traugutta 115b, Gdansk-Wrzeszcz 80-226'), ('DS3', 'Do Studzienki 32, Gdansk-Wrzeszcz 80-226'); INSERT INTO Pokoje(nazwa, pojemnosc, id_akademika) VALUES ('101a', 1, 1), ('101b', 2, 1), ('102a', 1, 1), ('102b', 2, 1), ('103a', 1, 1), ('103b', 2, 1), ('104a', 1, 1), ('104b', 2, 1), ('105a', 1, 1), ('105b', 2, 1), ('201a', 2, 2), ('201b', 2, 2), ('202a', 2, 2), ('202b', 2, 2), ('203a', 2, 2), ('203b', 2, 2), ('204a', 2, 2), ('204b', 2, 2), ('205a', 2, 2), ('205b', 2, 2), ('301a', 1, 3), ('301b', 2, 3), ('302a', 1, 3), ('302b', 2, 3), ('303a', 1, 3), ('303b', 2, 3), ('304a', 1, 3), ('304b', 2, 3), ('305a', 1, 3), ('305b', 2, 3); INSERT INTO Studenci(imie, nazwisko, rok_studiow, id_pokoju) VALUES ('Roman', 'Sawicki', 3, 1), ('Marcin', 'Szymczak', 3, 1), ('Joanna', 'Baranowska', 3, 3), ('Maciej', 'Szczepański', 3, 4), ('Czesław', 'Wróbel', 3, 6), ('Grażyna', 'Górska', 3, 8), ('Wanda', 'Krawczyk', 3, 8), ('Renata', 'Urbańska', 3, 9), ('Wiesława', 'Tomaszewska', 3, 9), ('Bożena', 'Baranowska', 3, 10), ('Ewelina', 'Malinowska', 3, 10), ('Anna', 'Krajewska', 3, 11), ('Mieczysław', 'Zając', 3, 12), ('Wiesław', 'Przybylski', 3, 12), ('Dorota', 'Tomaszewska', 3, 13), ('Jerzy', 'Wróblewski', 3, 13), ('Magdalena', 'Adamczyk', 3, 14), ('Władysław', 'Piotrowski', 3, 15), ('Marek', 'Wiśniewski', 3, 15), ('Stanisława', 'Głowacka', 3, 16), ('Agata', 'Kubiak', 3, 17); INSERT INTO Komputery ( host, IP, MAC, id_studenta ) SELECT CONCAT(imie, nazwisko), CAST(id AS varchar(20)), CAST(id AS varchar(20)), id FROM Studenci ; INSERT INTO Zawody(nazwa) VALUES ('Portier'), ('Woźny'), ('Ochrona'), ('Konserwator powierzchni płaskich'); INSERT INTO Pracownicy(imie, nazwisko, id_zawodu) VALUES ('Henryk', 'Kowalski', 1), ('Kazimiera', 'Zalewska', 1), ('Sylwia', 'Kaźmierczak', 1), ('Dorota', 'Maciejewska', 2), ('Jacek', 'Laskowski', 2), ('Michał', 'Sobczak', 2), ('Genowefa', 'Lis', 3), ('Mirosław', 'Czerwiński', 3), ('Agata', 'Gajewska', 3), ('Zofia', 'Bąk', 3), ('Marek', 'Adamczyk', 4), ('Agata', 'Pawlak', 4), ('Adam', 'Jankowski', 4); INSERT INTO Pracownicy_akademika(id_akademika, id_pracownika) VALUES (1, 1), (1, 2), (1, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (3, 8), (3, 9), (3, 1), (3, 2);
true
c16b60f6f66070d769b45db6a3ab5fb771d15cd9
SQL
Ncebakazi26/registration_numbers_webapp
/tables.sql
UTF-8
621
3.65625
4
[]
no_license
create table towns ( town_id serial not null primary key, town_name text not null, reg_string text not null ); create table registrationnumbers( id serial not null primary key, registration_num text not null, town_id int not null, foreign key (town_id) references towns (town_id) ); insert into towns (town_name, reg_string) values ('Cape Town', 'CA'); insert into towns (town_name, reg_string) values ('Bellville ', 'CY'); insert into towns (town_name, reg_string) values ('Paarl', 'CL'); -- alter table towns add constraint uniq_desc_constraint unique(town_name); -- database name = registration_numbers1
true
6fdeab9727d43eb3cf6dadc3506b9fab9661ff34
SQL
ESSeRE-Lab/qualitas.class-corpus
/projects/castor-1.3.3/cpactf/src/test/ddl/org/castor/cpa/test/test86/sapdb-create.sql
UTF-8
343
2.546875
3
[]
no_license
create sequence test86_circ_brother_seq // create table test86_circ_brother ( brother_id integer not null, brother_sibling integer, primary key (brother_id) ) // create sequence test86_circ_sister_seq // create table test86_circ_sister ( sister_id integer not null, sister_sibling integer, primary key (sister_id) ) //
true
25ec074bb69e9265b88efd4bed26d141ff671034
SQL
toha0730/user-device-ms
/schema.sql
UTF-8
2,950
4.0625
4
[]
no_license
-- ISYS2120 Assignment 3 Database -- Note: This uses PostgreSQL's non-standard MONEY data type. -- NUMERIC or DECIMAL is an acceptable alternative in these cases. -- Note however that it is a bad idea to store monetary values as -- floating point numbers due to rounding errors, so using REAL et al -- should be avoided in such cases. DROP TABLE IF EXISTS Model CASCADE; DROP TABLE IF EXISTS Department CASCADE; DROP TABLE IF EXISTS Offices CASCADE; DROP TABLE IF EXISTS ModelAllocations CASCADE; DROP TABLE IF EXISTS Employee CASCADE; DROP TABLE IF EXISTS EmployeePhoneNumbers CASCADE; DROP TABLE IF EXISTS EmployeeDepartments CASCADE; DROP TABLE IF EXISTS Device CASCADE; DROP TABLE IF EXISTS DeviceUsedBy CASCADE; DROP TABLE IF EXISTS Service CASCADE; DROP TABLE IF EXISTS Repair CASCADE; BEGIN TRANSACTION; CREATE TABLE Model ( manufacturer VARCHAR(20), modelNumber VARCHAR(10), description VARCHAR(300), weight REAL, -- any numeric type PRIMARY KEY (manufacturer, modelNumber) ); CREATE TABLE Employee ( empid INTEGER PRIMARY KEY, name VARCHAR(30), homeAddress VARCHAR(50), dateOfBirth DATE, password VARCHAR(100) ); CREATE TABLE Department ( name VARCHAR(20) PRIMARY KEY, budget MONEY, manager INTEGER REFERENCES Employee(empid) ON DELETE CASCADE-- manager of the department ); CREATE TABLE ModelAllocations ( manufacturer VARCHAR(20), modelNumber VARCHAR(10), department VARCHAR(20) REFERENCES Department(name), maxNumber INTEGER NOT NULL, PRIMARY KEY (manufacturer, modelNumber, department), FOREIGN KEY (manufacturer, modelNumber) REFERENCES Model ); CREATE TABLE Offices ( department VARCHAR(20) REFERENCES Department(name), location VARCHAR(50), PRIMARY KEY (department, location) ); CREATE TABLE EmployeePhoneNumbers ( empID INTEGER REFERENCES Employee ON DELETE CASCADE, phoneNumber CHAR(10), PRIMARY KEY (empID, phoneNumber) ); CREATE TABLE EmployeeDepartments ( empID INTEGER REFERENCES Employee ON DELETE CASCADE, department VARCHAR(20) REFERENCES Department(name), fraction NUMERIC NOT NULL, -- any non-integer numeric type PRIMARY KEY (empID, department) ); CREATE TABLE Device ( deviceID INTEGER PRIMARY KEY, serialNumber VARCHAR(10), purchaseDate DATE, purchaseCost MONEY, manufacturer VARCHAR(20) NOT NULL, modelNumber VARCHAR(10) NOT NULL, issuedTo INTEGER REFERENCES Employee(empID) ON DELETE CASCADE, FOREIGN KEY (manufacturer, modelNumber) REFERENCES Model ); CREATE TABLE DeviceUsedBy ( deviceID INTEGER, empID INTEGER, PRIMARY KEY (deviceID, empID) ); CREATE TABLE Service ( abn NUMERIC(11) PRIMARY KEY, -- or alternatively CHAR(11) - INTEGER is too small serviceName VARCHAR(20), email VARCHAR(300), owed MONEY ); CREATE TABLE Repair ( repairID INTEGER PRIMARY KEY, faultReport VARCHAR(60), startDate DATE, endDate DATE, cost MONEY, doneBy NUMERIC(11) REFERENCES Service(abn) NOT NULL, doneTo INTEGER REFERENCES Device(deviceID) NOT NULL ); COMMIT;
true
b0f9eac4461a18258ec7f7d864a8b9c6d62ec8e9
SQL
ruiborda/escalafon
/escalafon.sql
UTF-8
1,349
3.046875
3
[ "MIT" ]
permissive
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for usuario -- ---------------------------- DROP TABLE IF EXISTS `usuario`; CREATE TABLE `usuario` ( `id` int UNSIGNED NOT NULL AUTO_INCREMENT, `tipo_identificacion` enum('DNI','CARNET_DE_EXTRANJERIA') CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT 'DNI', `identificacion` int UNSIGNED NULL DEFAULT NULL, `nombres` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `apellidoPaterno` varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `apellidoMaterno` varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `usuario_identificacion_unique`(`identificacion`) USING BTREE, UNIQUE INDEX `usuario_id_unique`(`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of usuario -- ---------------------------- -- password admin INSERT INTO `usuario` VALUES (1, 'DNI', 12345678, 'JHON', 'DOE', 'DAS', 'JHON@GMAIL.COM', '8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918'); SET FOREIGN_KEY_CHECKS = 1;
true
bb6dab33ee99d676cbbaa8c5514cef5bda863f89
SQL
BATO-FR/lancement
/stop.sql
UTF-8
3,612
3.75
4
[]
no_license
DROP VIEW IF EXISTS export; CREATE VIEW export AS SELECT osm_id, osm_type, tags->'train' AS train, tags->'subway' AS subway, tags->'tram' AS tram, tags->'bus' AS bus, tags->'highway' AS highway, tags->'line' AS line, tags->'trolleybus' AS trolleybus, tags->'public_transport' AS public_transport, tags->'amenity' AS amenity, tags->'name' AS name, tags->'ref' AS ref, tags->'route_ref' AS route_ref, tags->'uic_ref' AS uic_ref, tags->'uic_name' AS uic_name, tags->'operator' AS operator, tags->'railway' AS railway, tags->'network' AS network, tags->'shelter' AS shelter, tags->'STIF:zone' AS "STIF:zone", tags->'type:RATP' AS "type:RATP", tags->'bench' AS bench, tags->'tactile_paving' AS tactile_paving, tags->'source_date' AS source_date, tags->'wheelchair' AS wheelchair, tags->'website' AS website, tags->'note' AS note, tags->'description' AS description, tags->'source' AS source, geom, tags - ARRAY['train', 'subway', 'tram', 'bus', 'highway', 'line', 'trolleybus', 'public_transport', 'amenity', 'name', 'ref', 'route_ref', 'uic_ref', 'uic_name', 'operator', 'railway', 'network', 'shelter', 'STIF:zone', 'type:RATP', 'bench', 'tactile_paving', 'source_date', 'wheelchair', 'website', 'note', 'description', 'source'] AS tags, tstamp FROM (( SELECT DISTINCT ON (nodes.id) nodes.id AS osm_id, CAST('n' AS TEXT) AS osm_type, nodes.tags, nodes.geom, nodes.tstamp FROM relations JOIN relation_members ON relations.id = relation_members.relation_id AND relation_members.member_type = 'N' AND relation_members.member_role IN ('stop', 'stop_entry_only', 'stop_exit_only', 'forward:stop', 'backward:stop') JOIN nodes ON relation_members.member_id = nodes.id AND nodes.tags->'public_transport' = 'stop_position' WHERE relations.tags->'type' = 'route' ) UNION ( SELECT DISTINCT ON (ways.id) ways.id AS osm_id, CAST('w' AS TEXT) AS osm_type, ways.tags, way_locate(ways.linestring) AS geom, ways.tstamp FROM relations JOIN relation_members ON relations.id = relation_members.relation_id AND relation_members.member_type = 'W' AND relation_members.member_role IN ('stop', 'stop_entry_only', 'stop_exit_only', 'forward:stop', 'backward:stop') JOIN ways ON relation_members.member_id = ways.id AND ways.tags->'public_transport' = 'stop_position' WHERE relations.tags->'type' = 'route' ) UNION ( SELECT nodes.id AS osm_id, CAST('n' AS TEXT) AS osm_type, nodes.tags, nodes.geom, nodes.tstamp FROM nodes LEFT JOIN relation_members ON relation_members.member_id = nodes.id AND relation_members.member_type = 'N' LEFT JOIN relations ON relations.id = relation_members.relation_id AND relations.tags->'type' = 'route' WHERE relations.id IS NULL AND ( nodes.tags->'highway' = 'bus_stop' OR nodes.tags->'railway' IN ('station', 'halt', 'tram_stop') ) ) UNION ( SELECT ways.id AS osm_id, CAST('w' AS TEXT) AS osm_type, ways.tags, way_locate(ways.linestring) AS geom, ways.tstamp FROM ways LEFT JOIN relation_members ON relation_members.member_id = ways.id AND relation_members.member_type = 'W' LEFT JOIN relations ON relations.id = relation_members.relation_id AND relations.tags->'type' = 'route' WHERE relations.id IS NULL AND ( ways.tags->'highway' = 'bus_stop' OR ways.tags->'railway' IN ('station', 'halt', 'tram_stop') ) )) AS t ;
true
14232dd6c5d6890a9c11366fc793c09bdbcb69e5
SQL
tantraa21/CI-1218013
/ri32-konversiUkuranFile/ri32_db.sql
UTF-8
1,620
3.03125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 3.2.4 -- http://www.phpmyadmin.net -- -- Host: localhost -- Waktu pembuatan: 07. Juli 2013 jam 10:51 -- Versi Server: 5.1.41 -- Versi PHP: 5.3.1 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!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: `ri32_db` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `tbl_user` -- CREATE TABLE IF NOT EXISTS `tbl_user` ( `id_user` int(9) NOT NULL AUTO_INCREMENT, `nama_depan` varchar(50) NOT NULL, `nama_belakang` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `kelamin` enum('pria','wanita') NOT NULL, `photo` varchar(100) NOT NULL, `ukuran` int(12) NOT NULL, `type` varchar(100) NOT NULL, PRIMARY KEY (`id_user`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ; -- -- Dumping data untuk tabel `tbl_user` -- INSERT INTO `tbl_user` (`id_user`, `nama_depan`, `nama_belakang`, `email`, `password`, `kelamin`, `photo`, `ukuran`, `type`) VALUES (14, 'Agus', 'Sumarna', 'agus_sumarna@ri32.com', 'agus123', 'pria', '101157-Agus Sumarna.png', 369690, 'image/png'), (15, 'Nafisah', 'Hurin', 'hurin_nafisah@yahoo.com', 'hurin123', 'wanita', '101140-Happy Ramadhan.jpg', 103626, 'image/jpeg'); /*!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
04d6518f882f55cea6dc20c10673f0e7f203a6ce
SQL
imajaydwivedi/SQLDBA-SSMS-Solution
/SQL Jobs/__General-Queries.sql
UTF-8
464
3.234375
3
[ "MIT" ]
permissive
use dba select * from dbo.CommandLog r where r.StartTime >= '2020-02-10 06:00:01.120' and r.StartTime <= '2020-02-10 08:00:01.120' and DatabaseName in ('StagingFiltered') --and ErrorMessage is not null -- 2020-02-10 07:17:57.660 select * from dbo.WhoIsActive_ResultSets r where r.collection_time >= '2020-02-10 07:00:01.120' and r.collection_time <= '2020-02-10 08:00:01.120' and r.program_name in ('SQL Job = DBA - IndexOptimize_Modified - StagingFiltered')
true
9913f88e41fa5eb84aa2c72723f959c2c7bc5083
SQL
prottasha01/rms
/rmsystem.sql
UTF-8
8,359
3.046875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Feb 10, 2020 at 12:17 PM -- Server version: 10.4.6-MariaDB -- PHP Version: 7.3.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `razia_sultana` -- -- -------------------------------------------------------- -- -- Table structure for table `batch` -- CREATE TABLE `batch` ( `batch_id` int(110) NOT NULL, `batch_no` varchar(110) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `batch` -- INSERT INTO `batch` (`batch_id`, `batch_no`) VALUES (6, '22nd'), (7, '23rd'), (9, '24th'); -- -------------------------------------------------------- -- -- Table structure for table `course` -- CREATE TABLE `course` ( `crs_id` int(110) NOT NULL, `crs_code` int(110) NOT NULL, `crs_title` varchar(110) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `course` -- INSERT INTO `course` (`crs_id`, `crs_code`, `crs_title`) VALUES (10, 222, 'C++'), (11, 333, 'java'), (12, 444, 'c'), (13, 0, 'physics'), (14, 106, 'bangla'); -- -------------------------------------------------------- -- -- Table structure for table `evaluates` -- CREATE TABLE `evaluates` ( `evaluates_id` int(11) NOT NULL, `teacher_id` int(110) NOT NULL, `crs_id` int(110) NOT NULL, `attendence` int(110) NOT NULL, `assignment` int(110) NOT NULL, `ct` int(110) NOT NULL, `midterm` int(110) NOT NULL, `final` int(110) NOT NULL, `total_mark` double NOT NULL, `grade` varchar(110) NOT NULL, `grade_point` double NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `evaluates` -- INSERT INTO `evaluates` (`evaluates_id`, `teacher_id`, `crs_id`, `attendence`, `assignment`, `ct`, `midterm`, `final`, `total_mark`, `grade`, `grade_point`) VALUES (1, 10, 10, 8, 8, 8, 22, 33, 0, '', 0), (2, 11, 11, 7, 7, 7, 18, 35, 0, '', 0), (3, 12, 12, 8, 8, 8, 22, 33, 0, '', 0), (4, 13, 13, 7, 7, 7, 18, 35, 0, '', 0), (5, 10, 10, 5, 5, 5, 22, 0, 0, '', 0), (6, 10, 10, 5, 5, 5, 20, 0, 0, 'A', 3.6), (7, 0, 0, 10, 10, 10, 30, 0, 0, '', 0), (8, 11, 11, 5, 5, 5, 20, 0, 0, 'A', 3.56), (9, 10, 10, 4, 4, 4, 12, 0, 0, '', 0); -- -------------------------------------------------------- -- -- Table structure for table `offered` -- CREATE TABLE `offered` ( `offered_id` int(11) NOT NULL, `batch_id` int(110) NOT NULL, `crs_id` int(110) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `offered` -- INSERT INTO `offered` (`offered_id`, `batch_id`, `crs_id`) VALUES (1, 5, 1), (2, 5, 1), (3, 7, 5), (4, 7, 5), (5, 9, 11), (6, 6, 10), (7, 6, 10), (8, 6, 10), (9, 6, 10), (10, 6, 10), (11, 6, 10); -- -------------------------------------------------------- -- -- Table structure for table `register` -- CREATE TABLE `register` ( `register_id` int(10) NOT NULL, `std_id` int(11) NOT NULL, `std_name` varchar(100) NOT NULL, `crs_id` int(11) NOT NULL, `crs_code` varchar(100) NOT NULL, `crs_title` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `register` -- INSERT INTO `register` (`register_id`, `std_id`, `std_name`, `crs_id`, `crs_code`, `crs_title`) VALUES (1, 5, '', 2, '', ''), (2, 3, '', 2, '', ''), (3, 10, '', 7, '', ''), (4, 10, '', 7, '', ''), (5, 10, '', 7, '', ''), (6, 10, '', 7, '', ''), (7, 7, '', 4, '', ''), (8, 1, '', 0, '', ''), (9, 1, '', 1, '', ''), (10, 1, '', 6, '', ''), (11, 15, '', 4, '', ''), (12, 15, '', 4, '', ''), (13, 20, '', 12, '', ''), (14, 20, '', 12, '', ''), (15, 20, '', 0, '', ''), (16, 17, '', 0, '', ''), (17, 17, '', 0, '', ''), (18, 19, '', 0, '', ''), (19, 18, '', 0, '', ''); -- -------------------------------------------------------- -- -- Table structure for table `retakes` -- CREATE TABLE `retakes` ( `retakes_id` int(11) NOT NULL, `std_id` int(110) NOT NULL, `crs_id` int(110) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `retakes` -- INSERT INTO `retakes` (`retakes_id`, `std_id`, `crs_id`) VALUES (1, 3, 1); -- -------------------------------------------------------- -- -- Table structure for table `student` -- CREATE TABLE `student` ( `std_id` int(110) NOT NULL, `std_name` varchar(110) NOT NULL, `std_roll` varchar(110) NOT NULL, `batch_no` varchar(110) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `student` -- INSERT INTO `student` (`std_id`, `std_name`, `std_roll`, `batch_no`) VALUES (17, 'shurovi', '114CSE0009', '22nd'), (18, 'rima', '114CSEoo14', '22nd'), (19, 'shifa', '1123CSE54', '24th'), (20, 'jakia', '114CSE4546546', '23rd'); -- -------------------------------------------------------- -- -- Table structure for table `teacher` -- CREATE TABLE `teacher` ( `teacher_id` int(110) NOT NULL, `teacher_name` varchar(110) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `teacher` -- INSERT INTO `teacher` (`teacher_id`, `teacher_name`) VALUES (12, 'Naima Mam'), (13, 'Noman'); -- -------------------------------------------------------- -- -- Table structure for table `teaching` -- CREATE TABLE `teaching` ( `teaching_id` int(110) NOT NULL, `teacher_id` int(110) NOT NULL, `crs_id` int(110) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `teaching` -- INSERT INTO `teaching` (`teaching_id`, `teacher_id`, `crs_id`) VALUES (1, 10, 0), (2, 10, 0), (3, 10, 0), (4, 11, 0), (5, 11, 0), (6, 10, 3), (7, 10, 3), (8, 11, 2), (9, 10, 11), (10, 12, 11), (11, 10, 10), (12, 12, 12), (13, 12, 12), (14, 12, 12), (15, 10, 10), (16, 13, 12), (17, 11, 11); -- -- Indexes for dumped tables -- -- -- Indexes for table `batch` -- ALTER TABLE `batch` ADD PRIMARY KEY (`batch_id`); -- -- Indexes for table `course` -- ALTER TABLE `course` ADD PRIMARY KEY (`crs_id`); -- -- Indexes for table `evaluates` -- ALTER TABLE `evaluates` ADD PRIMARY KEY (`evaluates_id`); -- -- Indexes for table `offered` -- ALTER TABLE `offered` ADD PRIMARY KEY (`offered_id`); -- -- Indexes for table `register` -- ALTER TABLE `register` ADD PRIMARY KEY (`register_id`); -- -- Indexes for table `retakes` -- ALTER TABLE `retakes` ADD PRIMARY KEY (`retakes_id`); -- -- Indexes for table `student` -- ALTER TABLE `student` ADD PRIMARY KEY (`std_id`); -- -- Indexes for table `teacher` -- ALTER TABLE `teacher` ADD PRIMARY KEY (`teacher_id`); -- -- Indexes for table `teaching` -- ALTER TABLE `teaching` ADD PRIMARY KEY (`teaching_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `batch` -- ALTER TABLE `batch` MODIFY `batch_id` int(110) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT for table `course` -- ALTER TABLE `course` MODIFY `crs_id` int(110) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT for table `evaluates` -- ALTER TABLE `evaluates` MODIFY `evaluates_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `offered` -- ALTER TABLE `offered` MODIFY `offered_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT for table `register` -- ALTER TABLE `register` MODIFY `register_id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20; -- -- AUTO_INCREMENT for table `retakes` -- ALTER TABLE `retakes` MODIFY `retakes_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `student` -- ALTER TABLE `student` MODIFY `std_id` int(110) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21; -- -- AUTO_INCREMENT for table `teacher` -- ALTER TABLE `teacher` MODIFY `teacher_id` int(110) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT for table `teaching` -- ALTER TABLE `teaching` MODIFY `teaching_id` int(110) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; 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
9eebba8301ccf39c19af8079c42a233860f9b0e6
SQL
firas91187/SQLSERVER-COURSE
/16/Join_union.sql
UTF-8
761
3.28125
3
[]
no_license
SELECT ShoesModel , ShoesSize FROM [Shoes] UNION SELECT ShoesModel , ShoesSize FROM [KidsShoes] SELECT * FROM Customer; SELECT * FROM Shoes; SELECT * FROM Customer INNER JOIN Shoes ON Customer.size = Shoes.ShoesSize Where Customer.name = 'Ahmed' SELECT * FROM Customer LEFT JOIN Shoes ON Customer.size = Shoes.ShoesSize SELECT * FROM Customer RIGHT JOIN Shoes ON Customer.size = Shoes.ShoesSize SELECT * FROM Customer FULL JOIN Shoes ON Customer.size = Shoes.ShoesSize --Where Customer.name = 'Saad'' SELECT TEAMMENUS.MenuName AS 'اسم الفريق', LEAGUEMENUS.MenuName AS 'اسم الدوري' FROM MENUS AS TEAMMENUS INNER JOIN MENUS AS LEAGUEMENUS ON TEAMMENUS.parent_id = LEAGUEMENUS.id
true
b7e40658bb35ecaea4085bb92d152e07f5c85738
SQL
3dlink/opsu
/Config/Schema/coursebyusers.sql
UTF-8
2,130
3
3
[]
no_license
# ************************************************************ # Sequel Pro SQL dump # Version 4096 # # http://www.sequelpro.com/ # http://code.google.com/p/sequel-pro/ # # Host: Localhost (MySQL 5.6.21) # Database: mentr # Generation Time: 2015-06-01 15:05:27 +0000 # ************************************************************ /*!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 */; /*!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 */; # Dump of table coursebyusers # ------------------------------------------------------------ DROP TABLE IF EXISTS `coursebyusers`; CREATE TABLE `coursebyusers` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `like` int(11) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, `course_id` int(11) DEFAULT NULL, `course_title` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; LOCK TABLES `coursebyusers` WRITE; /*!40000 ALTER TABLE `coursebyusers` DISABLE KEYS */; INSERT INTO `coursebyusers` (`id`, `like`, `user_id`, `course_id`, `course_title`) VALUES (1,1,1,1,NULL), (2,NULL,1,2,NULL), (3,NULL,1,4,NULL), (4,NULL,1,5,NULL), (5,NULL,1,6,NULL), (6,NULL,1,7,NULL), (7,NULL,1,1,NULL), (8,NULL,1,2,NULL), (9,NULL,1,4,NULL), (10,NULL,1,5,NULL), (11,NULL,1,6,NULL), (12,NULL,1,7,NULL), (13,NULL,1,1,0), (14,NULL,1,2,0), (15,NULL,1,4,0), (16,NULL,1,5,0), (17,NULL,1,6,0), (18,NULL,1,7,0); /*!40000 ALTER TABLE `coursebyusers` ENABLE KEYS */; UNLOCK TABLES; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
true
381d64c963fefd6574235a8fdb8489db7690e6f6
SQL
pravinboppuri-zz/TweetAnalysis
/toptrending.sql
UTF-8
301
2.890625
3
[]
no_license
#view script create view if not exists tweet.toptrending as select * from `tweet.wordcount` where LENGTH(word)>=5 and word like '%eclip%' or word like '%lunar%' or word like '%moon%' or word like '%sun%' or word like '%planet%' or word like '%shine%' or word like '%beautiful%' order by count desc
true