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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1a8d63833057e768a696c3caafcfe1a2f59303ac | SQL | chaitanyarudraraju/Expense-Management-PHP7 | /expenselogindb.sql | UTF-8 | 3,747 | 2.953125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 24, 2019 at 11:45 AM
-- Server version: 10.1.29-MariaDB
-- PHP Version: 7.1.12
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: `expenselogindb`
--
-- --------------------------------------------------------
--
-- Table structure for table `admin`
--
CREATE TABLE `admin` (
`uname` varchar(200) NOT NULL,
`upass` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `admin`
--
INSERT INTO `admin` (`uname`, `upass`) VALUES
('chaitanya', 'chYO9Uzez.cJQ'),
('chaitanya', 'chYO9Uzez.cJQ');
-- --------------------------------------------------------
--
-- Table structure for table `income`
--
CREATE TABLE `income` (
`uid` int(11) NOT NULL,
`uname` varchar(200) NOT NULL,
`income` int(11) NOT NULL,
`expense` int(11) NOT NULL,
`date` date NOT NULL,
`balance` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `income`
--
INSERT INTO `income` (`uid`, `uname`, `income`, `expense`, `date`, `balance`) VALUES
(64, 'suryah', 0, 0, '0000-00-00', 0),
(65, 'chaithu1', 0, 0, '0000-00-00', 0),
(66, '123456', 0, 0, '0000-00-00', 0),
(67, 'chaitanya', 0, 0, '0000-00-00', 0),
(68, 'ManojKumar', 0, 0, '0000-00-00', 0),
(69, 'ManojKumar', 0, 0, '0000-00-00', 0),
(70, 'ManojKumar', 1000, 0, '2019-04-15', 1000),
(71, 'ManojKumar', 0, 100, '2019-04-15', -100),
(72, 'ManojKumar', 10000, 200, '2019-04-15', 9800),
(73, 'ManojKumar', 10000, 200, '2019-04-15', 9800),
(74, 'ManojKumar', 1000, 0, '2019-04-01', 1000),
(75, 'ManojKumar', 1000, 0, '2019-04-01', 1000),
(76, 'ManojKumar', 1000, 10, '2019-04-01', 990),
(77, 'ManojKumar', 1000, 10, '2019-04-01', 990),
(78, 'suryah', 10000, 0, '2019-04-14', 10000),
(79, 'suryah', 894775, 46, '2019-04-14', 894729),
(80, 'suryah', 766546, 487, '2019-04-15', 766059),
(81, 'suryah', 33982847, 972426, '2019-04-22', 33010421);
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`uid` int(11) NOT NULL,
`ufname` varchar(200) NOT NULL,
`uname` varchar(200) NOT NULL,
`upass` varchar(200) NOT NULL,
`uemail` varchar(200) NOT NULL,
`imglink` varchar(200) NOT NULL,
`type` int(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`uid`, `ufname`, `uname`, `upass`, `uemail`, `imglink`, `type`) VALUES
(27, 'suryah', 'suryah', 'suHSEMshX4BO.', 'suryah@gmail.com', 'uploads/', 0),
(28, 'chaithu1', 'chaithu1', 'ch/7cMOvjlyj.', 'chaithu1@gmail.com', 'uploads/', 0),
(32, 'ManojKumar', 'ManojKumar', 'MajZkB0VHu5Ns', 'ManojKumar@gmail.com', 'uploads/Capture.JPG', 0);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `income`
--
ALTER TABLE `income`
ADD PRIMARY KEY (`uid`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`uid`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `income`
--
ALTER TABLE `income`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=82;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33;
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 |
4206e503f31dc779b4d11f59d800e13d9ec9efb0 | SQL | CesarJrFontalvo/mensajesApp-java | /target/classes/com/platzi/bd/mensajes.sql | UTF-8 | 1,512 | 3.125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1:3306
-- Tiempo de generación: 29-09-2021 a las 19:05:01
-- Versión del servidor: 5.7.21
-- Versión de PHP: 7.2.4
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `mensajes_app`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `mensajes`
--
DROP TABLE IF EXISTS `mensajes`;
CREATE TABLE IF NOT EXISTS `mensajes` (
`id_mensaje` int(11) NOT NULL AUTO_INCREMENT,
`mensaje` varchar(200) NOT NULL,
`autor_mensaje` varchar(50) NOT NULL,
`fecha_mensaje` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id_mensaje`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `mensajes`
--
INSERT INTO `mensajes` (`id_mensaje`, `mensaje`, `autor_mensaje`, `fecha_mensaje`) VALUES
(1, 'primer mensaje', 'césar', '2021-09-29 05:00:00'),
(5, 'segundo mensaje', 'junior', '2021-09-29 19:04:34');
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 |
d5b2c0716c674537ca2a5035a30f381f55cca8a7 | SQL | EliteNguyen/SQL | /Thực hành 1/QUANLYNV.SQL | UTF-8 | 4,999 | 4.0625 | 4 | [] | no_license | CREATE DATABASE QLNV
ON (NAME='QLNV_DATA', FILENAME='C:\SQL\QLNV.MDF')
LOG ON (NAME='QLNV_LOG', FILENAME='C:\SQL\QLNV.LDF')
USE QLNV
--1// BẢNG VỊ TRÍ
CREATE TABLE VITRI
(
MaVT CHAR(4) PRIMARY KEY,
Mota nvarchar(30)
)
--2//BẢNG PHÒNG BAN
CREATE TABLE PHONGBAN
(
MaPB char(4) PRIMARY KEY,
TenPB NVARCHAR(10),
DiaChi NVARCHAR(40),
NgayTL DATE,
MaNV CHAR(4)
)
SET DATEFORMAT DMY
--3// BẢNG NHÂN VIÊN
CREATE TABLE NHANVIEN
(
MaNV CHAR(4) PRIMARY KEY,
TenNV NVARCHAR(30),
Phai BIT,
MaVT CHAR(4),
FOREIGN KEY (MaVT) REFERENCES VITRI(MaVT),
MaPB CHAR(4),
FOREIGN KEY (MaPB) REFERENCES PHONGBAN(MaPB),
Luong BIGINT,
NgayVL DATE
)
--4//THỰC HIỆN CÁC TRUY VẤN
--a. In ra danh sách các nhân viên (MaNV, TenNV, Phai: Ghi rõ Nam/Nữ) của phòng ’Tài Vụ’ và sắp xếp thứ tự tăng dần theo họ tên.
SELECT n.MaNV, TenNV, (CASE WHEN Phai=0 THEN N'Nữ' ELSE 'Nam' END) AS Phai
FROM NHANVIEN N, PHONGBAN P
WHERE N.MaPB=P.MAPB AND TenPB=N'Tài Vụ'
ORDER BY TenNV ASC
--b. In ra số lượng nhân viên của mỗi phòng ban (TenPB, Số lượng NV) và sắp xếp theo thứ tự tăng dần.
SELECT TenPB, COUNT(*) AS [SỐ LƯỢNG NV]
FROM NHANVIEN N, PHONGBAN P
WHERE N.MaPB=P.MaPB
GROUP BY TenPB
ORDER BY [SỐ LƯỢNG NV] ASC
--c. In ra tên của Trưởng phòng (TenNV, Phai) có lương cao nhất.
SELECT TOP 1 WITH TIES TenNV,(CASE WHEN Phai=0 THEN N'Nữ' ELSE 'Nam' END) AS Phai, Luong
FROM NHANVIEN N, VITRI V
WHERE N.MaVT=V.MaVT AND Mota=N'Trưởng phòng'
GROUP BY TenNV,Phai, Luong
ORDER BY Luong DESC
--d. In ra danh sách nhân viên (TenNV) có vị trí là chuyên viên và có lương cao nhất.
SELECT TOP 7 WITH TIES TenNV, (CASE WHEN Phai=0 THEN N'Nữ' ELSE 'Nam' END) AS Phai, Luong
FROM NHANVIEN N, VITRI V
WHERE N.MaVT=V.MaVT AND Mota=N'chuyên viên'
GROUP BY TenNV , Phai, Luong
ORDER BY Luong DESC
--e. In ra danh sách nhân viên (MaPNV, TenNV) có thâm niên làm việc tính đến năm 2010 nhỏ hơn 5 năm và sắp xếp theo thứ tự tăng dần.
SELECT MaNV, TenNV, CONVERT(VARCHAR(10), NgayVL, 103) AS [NGÀY VÀO LÀM]
FROM NHANVIEN
WHERE 2010-YEAR(NGAYVL) < 5
ORDER BY NgayVL ASC
--f. Tìm tên phòng ban (TenPB) có 5 nhân viên có lương từ 5.000.000 trở lên.
SELECT TOP 5 WITH TIES TenPB, TenNV, (CASE WHEN Phai=0 THEN N'Nữ' ELSE 'Nam' END) AS Phai, Luong
FROM PHONGBAN P, NHANVIEN N
WHERE P.MaPB=N.MaPB AND Luong > 5000000
GROUP BY TenPB, TenNV, Phai, Luong
ORDER BY LUONG DESC
--g. Đếm số lượng nhân viên của từng phòng ban. Hiển thị: Tên_PB, Số_người.
SELECT TenPB, COUNT(*) AS [SO LUONG NHAN VIEN]
FROM NHANVIEN N , PHONGBAN P
WHERE N.MaPB=P.MaPB
GROUP BY TenPB
--h. In ra tên phòng ban có từ 4 nhân viên trở lên.
SELECT TenPB, COUNT(*) [SO LUONG NV]
FROM NHANVIEN N, PHONGBAN P
WHERE N.MaPB=P.MaPB
GROUP BY TenPB
HAVING COUNT(*) > 4
--i. Hãy tính tổng tiền lương của từng phòng ban.
SELECT P.MaPB, TenPB, SUM(Luong) as [TIEN LUONG]
FROM PHONGBAN P , NHANVIEN N
WHERE P.MaPB=N.MaPB
GROUP BY P.MaPB, TenPB
--j. In ra thông tin của nhân viên cùng số năm công tác (tính đến thời điểm hiện tại). Hiển thị: Mã NV, Tên NV, Số năm công tác.
SELECT MaNV, TenNV, YEAR(GETDATE())-YEAR(NgayVL) as [SO NAM CONG TAC]
FROM NHANVIEN
--k. In ra tên phòng ban cùng tên của trưởng phòng.
SELECT TenPB, TenNV
FROM PHONGBAN P, NHANVIEN N, VITRI V
WHERE P.MaPB=N.MaPB AND N.MaVT=V.MaVT AND Mota=N'Trưởng phòng'
--l. In ra tên các nhân viên không là trưởng của các phòng ban.
SELECT TenNV, Mota
FROM NHANVIEN N, PHONGBAN P, VITRI V
WHERE P.MaPB=N.MaPB AND N.MaVT=V.MaVT AND V.MaVT NOT IN (SELECT V.MaVT
FROM NHANVIEN N , VITRI V
WHERE N.MaVT=V.MaVT AND Mota=N'Trưởng phòng')
--m. Thêm mới 1 NV bằng lệnh INSERT INTO:
--(‘NV016‘, ‘Đặng Nguyễn Ngân Vinh‘, 1, ‘VT04‘, ‘P005‘, 12000000, ‘20/10/2017‘)
INSERT INTO NHANVIEN(MaNV, TenNV, Phai, MaVT, MaPB, Luong, NgayVL) VALUES ('N017', N'Đặng Nguyễn Ngân Vinh',1, 'VT03', 'P004', 12000000, '20/10/2007')
-- KHI NHẬP THÔNG TIN MỚI Ở BẢNG NHÂN VIÊN ,
-- ĐẾN PHẦN MAVT NÓ SẼ CHIẾU ĐẾN BẢNG CHA LÀ VITRI NẾU MÃ VỊ TRÍ MÀ MÌNH NHẬP KHÔNG TRÙNG VỚI MAVT CỦA BẢNG CHA THÌ MAY SẼ KHÔNG CHO NHẬP VÀ BÁO LỖI ,
--ĐẾN PHẦN MAPB NÓ SẼ CHIẾU ĐẾN BẢNG CHA LÀ PHONGBAN VÀ CŨNG TƯƠNG TỰ NHƯ MÃ VỊ TRÍ ,
--BỎ KÍ TỰ "V" TRONG MÃ NHÂN VIÊN VÌ KHÓA CỦA MÌNH CHỈ CÓ 4 KÍ TỰ , PHẢI SỬA 16 THÀNH 17 VÌ TRÙNG MÃ NHÂN VIÊN ,
--MÁY SẼ KHÔNG CHO NHẬP.
--Nhận xét?
--n. Thêm mới 1 phòng ban sau: (‘P005‘, ‘Thanh tra-Pháp chế‘, ‘91 Nguyễn Chí Thanh‘, ‘10/10/2012‘, ‘N015‘). Nhận xét?
INSERT INTO PHONGBAN(MAPB, TenPB, DiaChi, NgayTL, MaNV) VALUES ('P005', N'TT-PC', N'91 Nguyễn Chí Thanh', '10/10/2012', 'N014')
| true |
031946a13caff2cc80101a3c5d801918cf41532d | SQL | muthuwebg/TV-api | /migration.sql | UTF-8 | 2,330 | 3.71875 | 4 | [
"MIT"
] | permissive | CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`token` varchar(255) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_active` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `index_user_email` (`email`),
KEY `index_user_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
CREATE TABLE `orders` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned DEFAULT NULL,
`plan_id` bigint(20) unsigned DEFAULT NULL,
`expiry_date` date DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_active` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `index_orders_expiry` (`expiry_date`),
KEY `fk_user_id` (`user_id`),
KEY `fk_plan_id` (`plan_id`),
CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`plan_id`) REFERENCES `plans` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1
CREATE TABLE `plans` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`name_short` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`price` int(11) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_active` tinyint(4) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `index_product_name` (`name`),
KEY `index_product_name_short` (`name_short`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
INSERT INTO `plans` (`id`, `name`, `name_short`, `description`, `price`, `created_at`, `updated_at`, `is_active`) VALUES
(1, 'Basic Plan', 'BP', 'The Basic plan give 80+ channels (Tamil, English, Hindi). This plan is valid for 30 days only.', 250, '2019-08-19 15:01:12', '2019-08-19 15:01:12', 1),
(2, 'Super Plan', 'SP', 'The Super plan give 100+ channels (Tamil, English, Hindi) and also gives internation channels. This plan is valid for 50 days only.', 350, '2019-08-19 15:02:08', '2019-08-19 15:02:08', 1); | true |
ae879ae07e12a4d8a0d9c5020c35a46729244c0a | SQL | lukepharr/dataHW | /HW8/HW8.sql | UTF-8 | 4,597 | 4.21875 | 4 | [] | no_license | Use Sakila;
#1a
select first_name, last_name from actor;
#1b
select concat(first_name, ' ', last_name) from actor;
#2a
select first_name, last_name, actor_id from actor
where first_name = 'Joe';
#2b
select first_name, last_name, actor_id from actor
where last_name like '%gen%';
#2c
select first_name, last_name, actor_id from actor
where last_name like '%li%'
order by last_name, first_name;
#2d
select country_id, country from country
where country in ('Afghanistan','Bangladesh','China');
#3a
alter table actor
add column middle_name varchar(100) after first_name;
#3b
alter table actor
modify middle_name blob;
#3c
alter table actor
drop middle_name;
#4a
select last_name, count(*) from actor group by last_name;
#4b
select last_name, count(*) from actor group by last_name
having count(*) > 1;
#4c
update actor set first_name = 'Harpo' where first_name = 'Groucho' and last_name='Williams';
#4d
update actor
set first_name = case when first_name='Harpo' then 'Groucho' else 'Mucho Groucho' end
where (actor_id=172);
#5a
show create table address;
#result: CREATE TABLE `address` (\n `address_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,\n `address` varchar(50) NOT NULL,\n `address2` varchar(50) DEFAULT NULL,\n `district` varchar(20) NOT NULL,\n `city_id` smallint(5) unsigned NOT NULL,\n `postal_code` varchar(10) DEFAULT NULL,\n `phone` varchar(20) NOT NULL,\n `location` geometry NOT NULL,\n `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`address_id`),\n KEY `idx_fk_city_id` (`city_id`),\n SPATIAL KEY `idx_location` (`location`),\n CONSTRAINT `fk_address_city` FOREIGN KEY (`city_id`) REFERENCES `city` (`city_id`) ON UPDATE CASCADE\n) ENGINE=InnoDB AUTO_INCREMENT=606 DEFAULT CHARSET=utf8
#6a
select staff.first_name, staff.last_name, address.address
from staff
inner join address
on staff.address_id=address.address_id;
#6b
select staff.first_name, staff.last_name, sum(payment.amount) as 'total payment amount'
from staff
inner join payment
on staff.staff_id=payment.staff_id
where month(payment.payment_date)=8 and year(payment.payment_date)=2005
group by first_name, last_name;
#6c
select film.title, count(film_actor.actor_id) as 'cast count'
from film
inner join film_actor
on film.film_id=film_actor.film_id
group by film.title;
#6d
select film.film_id, count(inventory.inventory_id) as 'inventory count'
from film
inner join inventory
on film.film_id=inventory.film_id
where film.title='Hunchback Impossible'
group by film.film_id;
#6e
select customer.first_name, customer.last_name, sum(payment.amount) as 'total payment'
from customer
inner join payment
on payment.customer_id=customer.customer_id
group by customer.first_name, customer.last_name
order by customer.last_name;
#7a
select title from film
where title like 'k%' or title like 'q%'
and language_id in(
select language_id from language
where language.name='english');
#7b
select first_name, last_name from actor
where actor_id in(
select film_actor.actor_id from film_actor
where film_actor.film_id in(
select film.film_id from film
where film.title = 'Alone Trip'));
#7c
select email from customer
where address_id in (
select address.address_id from address
where address.city_id in(
select city.city_id from city
where city.country_id in(
select country.country_id from country
where country.country='canada')));
#7d
select title, film_id from film
where film_id in(
select film_category.film_id from film_category
where category_id in(
select category.category_id from category
where category.name='family'));
#7e
select film.title, count(rental.inventory_id) as 'times rented'
from film
inner join inventory
on film.film_id = inventory.film_id
inner join rental
on inventory.inventory_id=rental.inventory_id
group by film.title
order by count(rental.inventory_id) desc;
#7f
select staff.store_id, sum(payment.amount) as 'total earnings'
from staff
inner join payment
on staff.staff_id=payment.staff_id
group by staff.store_id;
#7g
select store.store_id, city.city, country.country
from store
inner join city
on (select address.city_id from address where address.address_id in (store.address_id))=city.city_id
inner join country
on (select city.country_id from city where city.city_id in (select address.city_id from address where address.address_id in (store.address_id)))=country.country_id;
#8a
create view myview as
select staff.store_id, sum(payment.amount) as 'total earnings'
from staff
inner join payment
on staff.staff_id=payment.staff_id
group by staff.store_id;
#8b
select * from myview;
#8c
drop view myview; | true |
eb331a441dc65fb7570d6a2efc66c466fdc56bad | SQL | bellmit/origin | /family_order/sql/.svn/pristine/eb/eb331a441dc65fb7570d6a2efc66c466fdc56bad.svn-base | UTF-8 | 734 | 3.0625 | 3 | [] | no_license | select a.serial_number,b.switch_id moffice_id, a.remove_tag,a.destory_time,a.log_id,a.rsrv_str1,a.user_id,a.eparchy_code from tf_b_reuse_log a,td_m_moffice b
WHERE a.back_time >= TO_DATE(:START_DATE,'yyyy-mm-dd hh24:mi:ss')
AND a.back_time <= TO_DATE(:END_DATE,'yyyy-mm-dd hh24:mi:ss')
and a.eparchy_code = :EPARCHY_CODE
and a.eparchy_code = b.eparchy_code
and a.moffice_id = b.moffice_id
and (:LOG_ID IS NULL OR a.LOG_ID = :LOG_ID)
and (:RES_NO_S IS NULL OR a.SERIAL_NUMBER >= :RES_NO_S)
and (:RES_NO_E IS NULL OR a.SERIAL_NUMBER <= :RES_NO_E)
and (:BACK_TYPE_CODE is null or a.back_type_code = :BACK_TYPE_CODE)
and (:MOFFICE_ID is null or b.switch_id = :MOFFICE_ID)
and (:BACK_STAFF_ID is null or a.back_staff_id = :BACK_STAFF_ID ) | true |
ada1e955c1e5adabd31128e3dc73f1c89729ae17 | SQL | ErosMLima/Training-Jan-2021 | /Modules/SQL/Day6/Vatsal Parmar/SQLDay6SubqueryTask.sql | UTF-8 | 5,610 | 4.59375 | 5 | [] | no_license | /* Day 6 Subquery Task */
-- 1. Write a query to find the names (first_name, last_name) and salaries of the employees
--who have higher salary than the employee whose last_name='Bull'.
SELECT FirstName + ' ' + LastName 'Name',Salary
FROM Employees WHERE Salary > (SELECT Salary FROM Employees WHERE LastName='Bull');
-- 2. Find the names (first_name, last_name) of all employees who works in the
--IT department.
SELECT FirstName + ' ' + LastName 'Name'
FROM Employees WHERE DepartmentID =
(SELECT DepartmentID FROM Departments WHERE DepartmentName='IT');
-- 3. Find the names (first_name, last_name) of the employees who have a manager who
--works for a department based in United States.
SELECT FirstName + ' ' + LastName 'Name'
FROM Employees WHERE ManagerID IN
(SELECT ManagerID FROM Departments WHERE LocationID IN
(SELECT LocationID FROM Locations WHERE CountryID
=(SELECT CountryID FROM Countries WHERE CountryName = 'United States of America')
)
);
-- 4. Find the names (first_name, last_name) of the employees who are managers.
SELECT FirstName + ' ' + LastName 'Name'
FROM Employees WHERE EmployeeID IN(SELECT DISTINCT ManagerID FROM Employees);
-- 5. Find the names (first_name, last_name), salary of the employees whose salary
--is greater than the average salary.
SELECT FirstName + ' ' + LastName 'Name',Salary
FROM Employees WHERE Salary>(SELECT AVG(Salary) FROM Employees);
-- 6. Find the names (first_name, last_name), salary of the employees whose salary
--is equal to the minimum salary for their job grade.
SELECT FirstName + ' ' + LastName 'Name',Salary
FROM Employees WHERE Salary IN (SELECT MIN(Salary) FROM Employees GROUP BY JobId);
-- 7. Find the names (first_name, last_name), salary of the employees who earn more
--than the average salary and who works in any of the IT departments.
SELECT FirstName + ' ' + LastName 'Name',Salary
FROM Employees WHERE DepartmentID IN
(SELECT DepartmentID FROM Departments WHERE DepartmentName LIKE 'IT%') AND Salary>(SELECT AVG(Salary) FROM Employees);
-- 8. Find the names (first_name, last_name), salary of the employees who earn
--more than Mr. Bell.
SELECT FirstName + ' ' + LastName 'Name',Salary
FROM Employees WHERE Salary > (SELECT Salary FROM Employees WHERE FirstName='Bell');
-- 9. Find the names (first_name, last_name), salary of the employees who earn the
--same salary as the minimum salary for all departments.
SELECT FirstName + ' ' + LastName 'Name',Salary
FROM Employees WHERE Salary IN
(SELECT MIN(Salary) FROM Employees GROUP BY DepartmentID);
-- 10. Find the names (first_name, last_name), salary of the employees whose
--salary greater than average salary of all department.
SELECT FirstName + ' ' + LastName 'Name',Salary
FROM Employees WHERE Salary > ALL
(SELECT AVG(Salary) FROM Employees GROUP BY DepartmentID);
-- 11. Write a query to find the names (first_name, last_name) and salary of the
--employees who earn a salary that is higher than the salary of all the Shipping
--Clerk (JOB_ID = 'SH_CLERK'). Sort the results on salary from the lowest to highest.
SELECT FirstName + ' ' + LastName 'Name',Salary
FROM Employees WHERE Salary > ALL
(SELECT Salary FROM Employees WHERE JobId = 'SH_CLERK') ORDER BY Salary;
-- 12. Write a query to find the names (first_name, last_name) of the employees who are not supervisors.
SELECT e.FirstName + ' ' + e.LastName 'Name'
FROM Employees e WHERE NOT EXISTS(SELECT * FROM Employees em WHERE em.ManagerID = e.EmployeeID);
-- 13. Write a query to display the employee ID, first name, last names, and
--department names of all employees.
SELECT e.EmployeeID,e.FirstName,e.LastName,(SELECT d.DepartmentName FROM Departments d WHERE e.DepartmentID=d.DepartmentID) 'Department'
FROM Employees e ORDER BY Department;
-- 14. Write a query to display the employee ID, first name, last names, salary of
--all employees whose salary is above average for their departments.
SELECT e.EmployeeID, e.FirstName, e.LastName, e.Salary
FROM Employees e
WHERE e.Salary >
(SELECT AVG(Salary) FROM Employees em WHERE em.DepartmentID = e.DepartmentID);
-- 15. Write a query to fetch even numbered records from employees table.
SELECT * FROM Employees WHERE EmployeeID%2 != 0;
-- 16. Write a query to find the 5th maximum salary in the employees table.
SELECT DISTINCT e.Salary FROM Employees e
WHERE 5 = (SELECT COUNT(DISTINCT em.Salary)
FROM Employees em WHERE em.Salary >= e.Salary);
-- 17. Write a query to find the 4th minimum salary in the employees table.
SELECT DISTINCT e.Salary FROM Employees e
WHERE 4 = (SELECT COUNT(DISTINCT em.Salary)
FROM Employees em WHERE em.Salary <= e.Salary);
-- 18. Write a query to select last 10 records from a table.
SELECT TOP 10 * FROM Employees ORDER BY EmployeeID DESC;
-- 19. Write a query to list department number, name for all the departments
--in which there are no employees in the department.
SELECT * FROM Departments WHERE DepartmentID NOT IN (SELECT DepartmentID FROM Employees);
-- 20. Write a query to get 3 maximum salaries.
SELECT DISTINCT e.Salary FROM Employees e
WHERE 3>= (SELECT COUNT(DISTINCT em.Salary)
FROM Employees em WHERE em.Salary >= e.Salary) ORDER BY e.Salary DESC;
-- 21. Write a query to get 3 minimum salaries.
SELECT DISTINCT e.Salary FROM Employees e
WHERE 3>= (SELECT COUNT(DISTINCT em.Salary)
FROM Employees em WHERE em.Salary <= e.Salary) ORDER BY e.Salary DESC;
-- 22. Write a query to get nth max salaries of employees.
SELECT * FROM Employees e
WHERE 1=(
SELECT COUNT(DISTINCT em.Salary)
FROM Employees em
WHERE em.Salary > e.Salary
); | true |
8b4557ec13be00ea7faca163735f7e1f21d5fb46 | SQL | codegeartecnologia/prj_engenharia_front | /acadbd.sql | UTF-8 | 6,303 | 3.28125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 14-Maio-2015 às 03:14
-- Versão do servidor: 5.6.21
-- PHP Version: 5.6.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `acadbd`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `servico`
--
CREATE TABLE IF NOT EXISTS `servico` (
`id` bigint(20) unsigned NOT NULL,
`titulo` varchar(50) NOT NULL,
`descricao` varchar(255) NOT NULL,
`apresentacao` char(1) NOT NULL DEFAULT 'n',
`nome_imagem` varchar(255) NOT NULL,
`tipo_servico` varchar(50) NOT NULL,
`texto` text NOT NULL,
`datacad` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `servico`
--
INSERT INTO `servico` (`id`, `titulo`, `descricao`, `apresentacao`, `nome_imagem`, `tipo_servico`, `texto`, `datacad`) VALUES
(1, 'Edição do Teste 2', 'Edição do Teste 2', 'n', '5553ae3e4817e.png', 'Saneamento', 'Edição do Teste 2', '2015-05-11 20:08:09'),
(2, 'Edição do Teste 2', 'Edição do Teste 2', 'n', '55510c9936fe2.png', 'Obras', 'Edição do Teste 2.', '2015-05-11 20:10:01'),
(3, 'Teste 3', 'Teste3', 'n', '55510ecdb1a45.png', 'Obras', 'Test3', '2015-05-11 20:19:25'),
(4, 'Projeto Arquitetônico', 'Ao iniciar um projeto de arquitetura o arquiteto deve-se atentar para os procedimentos que o sistema exige.', 'n', '5551216be4949.png', 'Engenharia', 'Ao iniciar um projeto de arquitetura em alvenaria estrutural, o arquiteto deve atentar para os procedimentos que o sistema exige. O projeto arquitetônico deve ser desenvolvido desde o estudo de viabilidade levando-se em consideração o princípio dos "painéis" e a modulação da família de blocos previamente escolhida. Desta forma, o arquiteto desenvolve suas ideias e o programa de projeto definido com o cliente, já oferecendo soluções beneficiadas pelo potencial do sistema construtivo e não avançando além de suas limitações.', '2015-05-11 21:38:52'),
(5, 'Obras de Urbanização', 'Pavimentação, Urbanização e Revitalização', 'n', '5551342bf158b.png', 'Obras', 'Ttetste \r\nPavimentação, Urbanização e Revitalização\r\nPavimentação, Urbanização e Revitalização', '2015-05-11 22:58:52'),
(6, 'Saneamento', 'Revitalização do sistema de afluente da cidade de Ponta Grossa - PR', 'n', '555134bb2087b.png', 'Saneamento', 'Toda a extensão da orla da Praia da Tereza, no bairro Balneário em São Pedro da Aldeia, na Região dos Lagos do Rio, está passando por obras de drenagem, urbanização e revitalização. Nesta terça-feira (3), cerca de 50 metros de manilhas foram instaladas no local para a construção da rede de drenagem de águas pluviais. A obra é realizada por meio da Secretaria de Serviços Públicos.', '2015-05-11 23:01:15'),
(7, 'Obras de Urbanização', 'Obras em Jaguariaíva - PR', 'n', '55513569e220d.png', 'Obras', 'Obras em todas as ruas e avenidas de jaguariaíva - PR.', '2015-05-11 23:04:09'),
(8, 'Engenharia', 'Construção do posto Hospitalar em Arapoti - PR.', 'n', '5551366874f2e.png', 'Engenharia', 'Em Arapoti - PR foi construído um novo posto no centro da cidade para melhores atendimento ao povo aropotenses.', '2015-05-11 23:08:24');
-- --------------------------------------------------------
--
-- Estrutura da tabela `suporte`
--
CREATE TABLE IF NOT EXISTS `suporte` (
`id` int(11) NOT NULL,
`problema` varchar(255) NOT NULL,
`descricao` text NOT NULL,
`solucao` text NOT NULL,
`datacad` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estrutura da tabela `usuario`
--
CREATE TABLE IF NOT EXISTS `usuario` (
`id` bigint(20) unsigned NOT NULL,
`nome` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`senha` varchar(50) NOT NULL,
`administrador` char(1) NOT NULL DEFAULT 'n',
`ativo` char(1) NOT NULL DEFAULT 's',
`datacad` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `usuario`
--
INSERT INTO `usuario` (`id`, `nome`, `email`, `senha`, `administrador`, `ativo`, `datacad`) VALUES
(1, 'Djalma Manfrin', 'djalma@hotmail.com', '21232f297a57a5a743894a0e4a801fc3', 's', 's', '2015-03-17 23:28:17'),
(2, 'Teste', 'teste@hotmail.com', '698dc19d489c4e4db73e28a713eab07b', 'n', 's', '2015-03-18 00:15:05'),
(5, 'Julia Manfrin', 'julia.manfrin@site.com', '827ccb0eea8a706c4c34a16891f84e7b', 'n', 's', '2015-05-11 12:44:21'),
(6, 'Ana Caroline Manfrin', 'anac.manfrin@site.com', '827ccb0eea8a706c4c34a16891f84e7b', 'n', 's', '2015-05-11 12:47:06'),
(7, 'Gabriela Rodrigues', 'gabi@hotmail.com', '827ccb0eea8a706c4c34a16891f84e7b', 'n', 's', '2015-05-11 12:54:45'),
(21, 'Loudes Manfrin', 'lourdes.manfrin@site.com', '827ccb0eea8a706c4c34a16891f84e7b', 'n', 's', '2015-05-12 18:23:46'),
(22, 'Lucia Rodrigues', 'lucia.rodrigues@site.com', '81dc9bdb52d04dc20036dbd8313ed055', 'n', 's', '2015-05-12 18:25:48'),
(23, 'Tiago Manfrin', 'tiago@site.com', '827ccb0eea8a706c4c34a16891f84e7b', 'n', 's', '2015-05-12 18:28:49');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `servico`
--
ALTER TABLE `servico`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
--
-- Indexes for table `suporte`
--
ALTER TABLE `suporte`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `usuario`
--
ALTER TABLE `usuario`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`), ADD UNIQUE KEY `email` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `servico`
--
ALTER TABLE `servico`
MODIFY `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `suporte`
--
ALTER TABLE `suporte`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `usuario`
--
ALTER TABLE `usuario`
MODIFY `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=24;
/*!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 |
688a4841a97e1247b1f13720a4a33440a2f70f7a | SQL | dxd132630/AcademicProjects | /LibraryManagementProject/SQLschemaSetupQuaries/Creates_and_Triggers.sql | UTF-8 | 3,255 | 3.734375 | 4 | [] | no_license | CREATE SCHEMA LIBRARY;
USE LIBRARY;
CREATE TABLE BOOK ( Book_id varchar(10) not null,
Title varchar(100),
CONSTRAINT pk_book_id primary key (book_id));
CREATE TABLE BOOK_AUTHORS ( Book_id varchar(10) not null,
Author_name varchar(100) not null,
Fname varchar(20),
Minit varchar(10),
Lname varchar(20),
primary key (Book_id ,Author_name),
foreign key (Book_id) references BOOK (Book_id));
CREATE TABLE LIBRARY_BRANCH ( Branch_id int not null,
Branch_name varchar(20),
Address varchar(100),
primary key (Branch_id) );
CREATE TABLE BOOK_COPIES (Book_id varchar(10) not null,
Branch_id int not null,
No_of_copies int ,
primary key(Book_id ,Branch_id),
foreign key (Book_id) references BOOK (Book_id),
foreign key (Branch_id) references LIBRARY_BRANCH (Branch_id));
CREATE TABLE BORROWER (Card_no int not null,
Fname varchar(20) not null,
Lname varchar(20) not null,
Address varchar(50) not null,
Phone varchar (14),
primary key (Card_no));
CREATE TABLE BOOK_LOANS (Loan_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
Book_id varchar(10) not null,
Branch_id int not null,
Card_no int not null,
Date_out Date,
Due_date Date,
Date_in Date,
foreign key (Book_id) references BOOK (Book_id),
foreign key (Branch_id) references LIBRARY_BRANCH (Branch_id),
foreign key (Card_no) references BORROWER (Card_no));
CREATE TABLE FINE(Loan_id INT PRIMARY KEY ,
Fine_amt DECIMAL(5,2),
PAID BOOLEAN)ENGINE=INNODB;
SET sql_mode = 'NO_ZERO_DATE';
CREATE TRIGGER `FINES_AND_DUES` AFTER INSERT ON `book_loans`
FOR EACH ROW
BEGIN
DECLARE fine_amount decimal(5,2);
IF new.`date_in` IS NULL AND new.`due_date` < CURDATE() THEN
SET fine_amount = DATEDIFF(CURDATE(),new.`due_date`)*0.25;
INSERT INTO FINE VALUES (NEW.loan_id,fine_amount,0);
ELSEIF new.`date_in` IS NULL AND new.`due_date` >= CURDATE() THEN
SET fine_amount = 0.0;
INSERT INTO FINE VALUES (NEW.loan_id,fine_amount,0);
ELSEIF new.`date_in` IS NOT NULL AND new.`date_in` > new.`due_date` THEN
SET fine_amount = DATEDIFF(new.`date_in`,new.`due_date`)*0.25;
INSERT INTO FINE VALUES (NEW.loan_id,fine_amount,0);
ELSEIF new.`date_in` IS NOT NULL AND new.`date_in` <= new.`due_date` THEN
SET fine_amount = 0.0;
INSERT INTO FINE VALUES (NEW.loan_id,0.0,0);
END IF;
END;
CREATE TRIGGER `FINE_PAYMENT` AFTER UPDATE ON `book_loans`
FOR EACH ROW
BEGIN
DECLARE fine_amount decimal(5,2);
DECLARE loan_ids int ;
IF new.`date_in` IS NULL AND new.`due_date` < CURDATE() THEN
SET fine_amount = DATEDIFF(CURDATE(),new.`due_date`)*0.25;
SET loan_ids = new.`loan_id`;
UPDATE FINE F set F.`fine_amt`=fine_amount WHERE F.`loan_id`=loan_ids AND F.`paid`=0;
ELSEIF new.`date_in` IS NULL AND new.`due_date` >= CURDATE() THEN
SET fine_amount = 0.0;
UPDATE FINE F set F.`fine_amt`=fine_amount WHERE F.`loan_id`=loan_ids AND F.`paid`=0;
ELSEIF new.`date_in` IS NOT NULL AND new.`date_in` > new.`due_date` THEN
SET fine_amount = DATEDIFF(new.`date_in`,new.`due_date`)*0.25;
SET loan_ids = new.`loan_id`;
UPDATE FINE F set F.`fine_amt`=fine_amount WHERE F.`loan_id`=loan_ids AND F.`paid`=0;
ELSEIF new.`date_in` IS NULL AND new.`date_in` <= new.`due_date` THEN
SET fine_amount = 0.0;
SET loan_ids = new.`loan_id`;
UPDATE FINE F set F.`fine_amt`=fine_amount WHERE F.`loan_id`=loan_ids AND F.`paid`=0;
END IF;
END;
| true |
5996a4ab809fdcb7961018a9bf09a60dd920a5a6 | SQL | erifejams/CA-Project-Group-17 | /CA Project Group 17.ddl | UTF-8 | 7,294 | 3.25 | 3 | [
"MIT"
] | permissive | -- Generated by Oracle SQL Developer Data Modeler 19.2.0.182.1216
-- at: 2019-12-15 20:50:12 GMT
-- site: Oracle Database 12c
-- type: Oracle Database 12c
DROP TABLE branch CASCADE CONSTRAINTS;
DROP TABLE car CASCADE CONSTRAINTS;
DROP TABLE contract CASCADE CONSTRAINTS;
DROP TABLE customer CASCADE CONSTRAINTS;
DROP TABLE employee CASCADE CONSTRAINTS;
DROP TABLE final_bill CASCADE CONSTRAINTS;
DROP TABLE online_sales CASCADE CONSTRAINTS;
DROP TABLE sale CASCADE CONSTRAINTS;
CREATE TABLE branch (
branch_id NUMBER(7) NOT NULL,
branch_address NVARCHAR2(320),
branch_phone_number INTEGER,
booking_status VARCHAR2(50) NOT NULL
)
LOGGING;
ALTER TABLE branch ADD CONSTRAINT branch_pk PRIMARY KEY ( branch_id );
CREATE TABLE car (
registration_number INTEGER NOT NULL,
daily_cost NVARCHAR2(320),
details_of_manufacturer VARCHAR2(50),
model_id NUMBER(7),
car_category VARCHAR2(50),
type_of_fuel VARCHAR2(50),
mileage_after NUMBER(7, 2),
mileage_before NUMBER(7, 2)
)
LOGGING;
ALTER TABLE car ADD CONSTRAINT car_pk PRIMARY KEY ( registration_number );
CREATE TABLE contract (
contract_id NUMBER(7) NOT NULL,
rental_period INTEGER,
fuel_amount VARCHAR2(50),
booking_status VARCHAR2(50),
pickup_date DATE NOT NULL,
pickup_time DATE NOT NULL,
return_date DATE NOT NULL,
return_time DATE NOT NULL,
pickup_location NVARCHAR2(320) NOT NULL,
dropoff_location NVARCHAR2(320) NOT NULL,
customer_customer_id NUMBER(7),
mileage_before NUMBER(7, 2),
mileage_after NUMBER(7, 2),
car_registration_number INTEGER NOT NULL,
branch_branch_id NUMBER(7) NOT NULL,
sale_sale_id NUMBER(7) NOT NULL,
final_bill_amount_owed NUMBER(7, 2) NOT NULL
)
LOGGING;
CREATE UNIQUE INDEX contract__idx ON
contract (
sale_sale_id
ASC )
LOGGING;
CREATE UNIQUE INDEX contract__idxv1 ON
contract (
final_bill_amount_owed
ASC )
LOGGING;
ALTER TABLE contract ADD CONSTRAINT contract_pk PRIMARY KEY ( contract_id );
CREATE TABLE customer (
customer_id NUMBER(7) NOT NULL,
customer_name VARCHAR2(50) NOT NULL,
customer_age INTEGER NOT NULL,
customer_email NVARCHAR2(320) NOT NULL,
customer_address NVARCHAR2(320) NOT NULL
)
LOGGING;
ALTER TABLE customer ADD CONSTRAINT customer_ck_1 CHECK ( customer_age >= 18 );
ALTER TABLE customer ADD CONSTRAINT customer_ck_2 CHECK ( customer_email LIKE '%@%.com' );
ALTER TABLE customer ADD CONSTRAINT customer_pk PRIMARY KEY ( customer_id );
CREATE TABLE employee (
employee_id NUMBER(7) NOT NULL,
employee_address NVARCHAR2(320) NOT NULL,
employee_date_of_birth DATE NOT NULL,
employee_start_date DATE NOT NULL,
location_of_employment NVARCHAR2(320) NOT NULL,
branch_branch_id NUMBER(7),
employee_email_address NVARCHAR2(320) NOT NULL,
employee_name VARCHAR2(50) NOT NULL
)
LOGGING;
COMMENT ON COLUMN employee.location_of_employment IS
'head office or branch';
ALTER TABLE employee ADD CONSTRAINT employee_ck_1 CHECK ( employee_email_address LIKE '@speedyrentals.com' );
ALTER TABLE employee ADD CONSTRAINT employee_pk PRIMARY KEY ( employee_id );
CREATE TABLE final_bill (
amount_owed NUMBER(7, 2) NOT NULL
)
LOGGING;
ALTER TABLE final_bill ADD CONSTRAINT final_bill_pk PRIMARY KEY ( amount_owed );
CREATE TABLE online_sales (
transaction_state VARCHAR2(50) NOT NULL,
sale_sale_id NUMBER(7) NOT NULL
)
LOGGING;
CREATE UNIQUE INDEX online_sales__idx ON
online_sales (
sale_sale_id
ASC )
LOGGING;
ALTER TABLE online_sales ADD CONSTRAINT online_sales_pk PRIMARY KEY ( transaction_state );
CREATE TABLE sale (
sale_id NUMBER(7) NOT NULL,
employee_employee_id NUMBER(7) NOT NULL
)
LOGGING;
ALTER TABLE sale ADD CONSTRAINT sale_pk PRIMARY KEY ( sale_id );
ALTER TABLE contract
ADD CONSTRAINT contract_branch_fk FOREIGN KEY ( branch_branch_id )
REFERENCES branch ( branch_id )
NOT DEFERRABLE;
ALTER TABLE contract
ADD CONSTRAINT contract_car_fk FOREIGN KEY ( car_registration_number )
REFERENCES car ( registration_number )
NOT DEFERRABLE;
ALTER TABLE contract
ADD CONSTRAINT contract_customer_fk FOREIGN KEY ( customer_customer_id )
REFERENCES customer ( customer_id )
NOT DEFERRABLE;
ALTER TABLE contract
ADD CONSTRAINT contract_final_bill_fk FOREIGN KEY ( final_bill_amount_owed )
REFERENCES final_bill ( amount_owed )
NOT DEFERRABLE;
ALTER TABLE contract
ADD CONSTRAINT contract_sale_fk FOREIGN KEY ( sale_sale_id )
REFERENCES sale ( sale_id )
NOT DEFERRABLE;
ALTER TABLE employee
ADD CONSTRAINT employee_branch_fk FOREIGN KEY ( branch_branch_id )
REFERENCES branch ( branch_id )
NOT DEFERRABLE;
ALTER TABLE online_sales
ADD CONSTRAINT online_sales_sale_fk FOREIGN KEY ( sale_sale_id )
REFERENCES sale ( sale_id )
NOT DEFERRABLE;
ALTER TABLE sale
ADD CONSTRAINT sale_employee_fk FOREIGN KEY ( employee_employee_id )
REFERENCES employee ( employee_id )
NOT DEFERRABLE;
-- Oracle SQL Developer Data Modeler Summary Report:
--
-- CREATE TABLE 8
-- CREATE INDEX 3
-- ALTER TABLE 19
-- CREATE VIEW 0
-- ALTER VIEW 0
-- CREATE PACKAGE 0
-- CREATE PACKAGE BODY 0
-- CREATE PROCEDURE 0
-- CREATE FUNCTION 0
-- CREATE TRIGGER 0
-- ALTER TRIGGER 0
-- CREATE COLLECTION TYPE 0
-- CREATE STRUCTURED TYPE 0
-- CREATE STRUCTURED TYPE BODY 0
-- CREATE CLUSTER 0
-- CREATE CONTEXT 0
-- CREATE DATABASE 0
-- CREATE DIMENSION 0
-- CREATE DIRECTORY 0
-- CREATE DISK GROUP 0
-- CREATE ROLE 0
-- CREATE ROLLBACK SEGMENT 0
-- CREATE SEQUENCE 0
-- CREATE MATERIALIZED VIEW 0
-- CREATE MATERIALIZED VIEW LOG 0
-- CREATE SYNONYM 0
-- CREATE TABLESPACE 0
-- CREATE USER 0
--
-- DROP TABLESPACE 0
-- DROP DATABASE 0
--
-- REDACTION POLICY 0
-- TSDP POLICY 0
--
-- ORDS DROP SCHEMA 0
-- ORDS ENABLE SCHEMA 0
-- ORDS ENABLE OBJECT 0
--
-- ERRORS 0
-- WARNINGS 0
| true |
317f0b651144ffd2d06efc177dce974efad2d9dc | SQL | zxteloiv/problem-reservoir | /docs/database.sql | UTF-8 | 3,463 | 3.5 | 4 | [
"BSD-2-Clause",
"MIT"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.5.0.2
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 2015-12-01 13:08:27
-- 服务器版本: 10.0.17-MariaDB
-- PHP Version: 5.6.14
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `prs`
--
CREATE DATABASE IF NOT EXISTS `prs` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `prs`;
-- --------------------------------------------------------
--
-- 表的结构 `img_attachment`
--
CREATE TABLE `img_attachment` (
`img_id` int(10) UNSIGNED NOT NULL COMMENT '图片id',
`img_name` varchar(50) NOT NULL DEFAULT '''''' COMMENT '图片名',
`img_type` varchar(25) NOT NULL DEFAULT '''''' COMMENT '图片类型(MIME)',
`img_size` varchar(20) NOT NULL DEFAULT '''''' COMMENT '图片大小',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '文件提交时间',
`img` mediumblob NOT NULL COMMENT '图片内容'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- 表的结构 `problems`
--
CREATE TABLE `problems` (
`problem_id` int(10) UNSIGNED NOT NULL,
`course` varchar(50) NOT NULL DEFAULT '''''' COMMENT '所属课程',
`chapter` varchar(50) NOT NULL DEFAULT '''''' COMMENT '所属章节',
`points` smallint(5) UNSIGNED NOT NULL DEFAULT '0' COMMENT '分值,单位为0.1分',
`difficulty` tinyint(3) UNSIGNED NOT NULL DEFAULT '0' COMMENT '题目难度',
`description` varchar(255) NOT NULL DEFAULT '''''' COMMENT '其它描述',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
`modify_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
`content` longtext NOT NULL COMMENT '内容,json串,list of primitives',
`keypoints` varchar(255) NOT NULL DEFAULT '''''' COMMENT '知识点',
`states` tinyint(3) UNSIGNED NOT NULL DEFAULT '0' COMMENT '问题状态, 0:正常, 1:图片附件失效, etc.',
`years` varchar(50) NOT NULL DEFAULT '' COMMENT '考试年份',
`backup1` varchar(200) NOT NULL DEFAULT '' COMMENT '补充1',
`backup2` varchar(200) NOT NULL DEFAULT '' COMMENT '补充2'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='题库表';
--
-- Indexes for dumped tables
--
--
-- Indexes for table `img_attachment`
--
ALTER TABLE `img_attachment`
ADD PRIMARY KEY (`img_id`);
--
-- Indexes for table `problems`
--
ALTER TABLE `problems`
ADD PRIMARY KEY (`problem_id`),
ADD KEY `modify_time` (`modify_time`),
ADD KEY `course` (`course`),
ADD KEY `chapter` (`chapter`),
ADD KEY `keypoints` (`keypoints`),
ADD KEY `course_2` (`course`,`chapter`,`points`),
ADD KEY `course_3` (`course`,`chapter`,`difficulty`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `img_attachment`
--
ALTER TABLE `img_attachment`
MODIFY `img_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '图片id';
--
-- AUTO_INCREMENT for table `problems`
--
ALTER TABLE `problems`
MODIFY `problem_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
/*!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 |
470bac5eedde6cd6939d4aba530a9561ebb50f5f | SQL | silence-do-good/stress-test-Postgres-and-MySQL | /dump/low/day13/select0427.sql | UTF-8 | 191 | 2.765625 | 3 | [] | no_license |
SELECT timeStamp, temperature
FROM ThermometerObservation
WHERE timestamp>'2017-11-12T04:27:00Z' AND timestamp<'2017-11-13T04:27:00Z' AND SENSOR_ID='235009e5_9e65_4a06_a195_b9498ff0dd79'
| true |
29db3e10956eba99b7087f1e46fad88d1b383348 | SQL | hernan-alperin/urbix | /urbixagg.sql | UTF-8 | 910 | 2.640625 | 3 | [] | no_license | select * from
(select time, data as "1"
from bkn_result
where '2015-01-01' <= time and time <= '2015-05-05'
and variable_id = 1) as f1
full join
(select time, data as "2"
from bkn_result
where '2015-01-01' <= time and time <= '2015-05-05'
and variable_id = 2) as f2
using (time)
full join
(select time, data as "82"
from bkn_result
where '2015-01-01' <= time and time <= '2015-05-05'
and variable_id = 8) as f8
using (time)
full join
(select time, data as "12"
from bkn_result
where '2015-01-01' <= time and time <= '2015-05-05'
and variable_id = 12) as f12
using (time)
full join
(select time, data as "14"
from bkn_result
where '2015-01-01' <= time and time <= '2015-05-05'
and variable_id = 14) as f14
using (time)
full join
(select time, data as "16"
from bkn_result
where '2015-01-01' <= time and time <= '2015-05-05'
and variable_id = 16) as f16
using (time)
;
| true |
ddc924ede904e8273f21ae4fb3db98472d06e328 | SQL | shahidahaamir/phh | /generated-bdd.sql | UTF-8 | 1,992 | 3.84375 | 4 | [] | no_license | DROP DATABASE IF EXISTS `magasin`;
CREATE DATABASE `magasin`;
USE `magasin`;
-- ---
-- Table 'produits'
-- Liste des produits
-- ---
DROP TABLE IF EXISTS `produits`;
CREATE TABLE `produits` (
`idpr` INTEGER NOT NULL AUTO_INCREMENT ,
`titre` VARCHAR(45) NOT NULL,
`ref` VARCHAR(50) NOT NULL,
`prix` DOUBLE NOT NULL DEFAULT 0.0,
`photo` VARCHAR(255) NULL DEFAULT NULL,
`description` VARCHAR(250) NULL DEFAULT NULL,
`idcat` INTEGER NOT NULL,
PRIMARY KEY (`idpr`)
) COMMENT 'Liste des produits';
-- ---
-- Table 'paniers'
--
-- ---
DROP TABLE IF EXISTS `paniers`;
CREATE TABLE `paniers` (
`idpa` INTEGER NOT NULL AUTO_INCREMENT,
`date` DATETIME NULL DEFAULT now(),
`idcl` INTEGER NOT NULL,
PRIMARY KEY (`idpa`)
);
-- ---
-- Table 'etre_dans'
--
-- ---
DROP TABLE IF EXISTS `etre_dans`;
CREATE TABLE `etre_dans` (
`idpr` INTEGER NOT NULL,
`idpa` INTEGER NOT NULL,
`quantite` INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (`idpr`, `idpa`)
);
-- ---
-- Table 'categories'
--
-- ---
DROP TABLE IF EXISTS `categories`;
CREATE TABLE `categories` (
`idcat` INTEGER NOT NULL AUTO_INCREMENT,
`titre` VARCHAR(45) NOT NULL,
`description` VARCHAR(150) NULL DEFAULT NULL,
PRIMARY KEY (`idcat`)
);
-- ---
-- Table 'clients'
--
-- ---
DROP TABLE IF EXISTS `clients`;
CREATE TABLE `clients` (
`idcl` INTEGER NOT NULL AUTO_INCREMENT ,
`nom` VARCHAR(50) NOT NULL,
`prenom` VARCHAR(50) NULL DEFAULT NULL,
`mail` VARCHAR(50) NULL DEFAULT NULL,
`adresse` VARCHAR(150) NULL DEFAULT NULL,
`login` VARCHAR(50) NULL DEFAULT NULL,
`mdp` VARCHAR(250) NULL DEFAULT NULL,
PRIMARY KEY (`idcl`)
);
-- ---
-- Foreign Keys
-- ---
ALTER TABLE `produits` ADD FOREIGN KEY (idcat) REFERENCES `categories` (`idcat`);
ALTER TABLE `paniers` ADD FOREIGN KEY (idcl) REFERENCES `clients` (`idcl`);
ALTER TABLE `etre_dans` ADD FOREIGN KEY (idpr) REFERENCES `produits` (`idpr`);
ALTER TABLE `etre_dans` ADD FOREIGN KEY (idpa) REFERENCES `paniers` (`idpa`);
| true |
a54d1dafced6255050afbcb273700d2941bdf072 | SQL | boolean-dev/learn | /04-sharding-sphere/sql/dbuser0.sql | UTF-8 | 3,986 | 3.09375 | 3 | [] | no_license | -- --------------------------------------------------------
-- 主机: 127.0.0.1
-- 服务器版本: 5.7.24-log - MySQL Community Server (GPL)
-- 服务器OS: Win64
-- HeidiSQL 版本: 10.2.0.5599
-- --------------------------------------------------------
/*!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' */;
-- Dumping database structure for dbuser0
CREATE DATABASE IF NOT EXISTS `dbuser0` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `dbuser0`;
-- Dumping structure for table dbuser0.tb_user_0
CREATE TABLE IF NOT EXISTS `tb_user_0` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(50) NOT NULL COMMENT '名字',
`age` mediumint(9) NOT NULL DEFAULT '0' COMMENT '年龄',
`sex` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别:0无,1男,2女',
`create_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=398790076873572353 DEFAULT CHARSET=utf8 COMMENT='用户表0';
-- Dumping data for table dbuser0.tb_user_0: ~5 rows (大约)
/*!40000 ALTER TABLE `tb_user_0` DISABLE KEYS */;
INSERT INTO `tb_user_0` (`id`, `name`, `age`, `sex`, `create_time`, `update_time`) VALUES
(398783788726878208, '鄢剑涛', 12, 0, '2019-11-06 10:24:24', '2019-11-06 10:24:24'),
(398790059962138624, '鄢剑涛', 14, 0, '2019-11-06 10:49:19', '2019-11-06 10:49:19'),
(398790063053340672, '鄢剑涛', 14, 0, '2019-11-06 10:49:20', '2019-11-06 10:49:20'),
(398790065880301568, '鄢剑涛', 14, 0, '2019-11-06 10:49:21', '2019-11-06 10:49:21'),
(398790076873572352, '鄢剑涛', 14, 0, '2019-11-06 10:49:23', '2019-11-06 10:49:23');
/*!40000 ALTER TABLE `tb_user_0` ENABLE KEYS */;
-- Dumping structure for table dbuser0.tb_user_1
CREATE TABLE IF NOT EXISTS `tb_user_1` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(50) NOT NULL COMMENT '名字',
`age` mediumint(9) NOT NULL DEFAULT '0' COMMENT '年龄',
`sex` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别:0无,1男,2女',
`create_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=398790103641620481 DEFAULT CHARSET=utf8;
-- Dumping data for table dbuser0.tb_user_1: ~3 rows (大约)
/*!40000 ALTER TABLE `tb_user_1` DISABLE KEYS */;
INSERT INTO `tb_user_1` (`id`, `name`, `age`, `sex`, `create_time`, `update_time`) VALUES
(398790094946828288, '鄢剑涛', 15, 0, '2019-11-06 10:49:28', '2019-11-06 10:49:28'),
(398790099690586112, '鄢剑涛', 15, 0, '2019-11-06 10:49:29', '2019-11-06 10:49:29'),
(398790103641620480, '鄢剑涛', 15, 0, '2019-11-06 10:49:30', '2019-11-06 10:49:30');
/*!40000 ALTER TABLE `tb_user_1` ENABLE KEYS */;
-- Dumping structure for table dbuser0.tb_user_info
CREATE TABLE IF NOT EXISTS `tb_user_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` bigint(20) NOT NULL COMMENT '用户id',
`info` varchar(50) NOT NULL DEFAULT '' COMMENT '用户简介',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
-- Dumping data for table dbuser0.tb_user_info: ~0 rows (大约)
/*!40000 ALTER TABLE `tb_user_info` DISABLE KEYS */;
/*!40000 ALTER TABLE `tb_user_info` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
| true |
988acb575ea9de7be26683a8e77389341c0a3dbb | SQL | tommyiversonj/openmrs-config-pihemr | /configuration/reports/reportdescriptors/dataexports/sql/edTriage.sql | UTF-8 | 14,418 | 3.46875 | 3 | [] | no_license | CALL initialize_global_metadata();
-- set @startDate = '2019-07-01';
-- set @endDate = '2020-12-31';
SELECT encounter_type_id into @EDTriageEnc from encounter_type where uuid = '74cef0a6-2801-11e6-b67b-9e71128cae77';
SELECT encounter_type_id into @consEnc from encounter_type where uuid = '92fd09b4-5335-4f7e-9f63-b2a663fd09a6';
SELECT name into @consEncName from encounter_type where uuid = '92fd09b4-5335-4f7e-9f63-b2a663fd09a6';
select form_id into @consForm from form where uuid = 'a3fc5c38-eb32-11e2-981f-96c0fcb18276';
select form_id into @edNoteForm from form where uuid = '793915d6-f8d9-11e2-8ff2-fd54ab5fdb2a';
set @locale = global_property_value('default_locale', @locale);
drop temporary table if exists temp_ED_Triage;
create temporary table temp_ED_Triage
(
patient_id int(11),
encounter_id int(11),
visit_id int(11),
zlemr_id varchar(50),
dossier_id varchar(50),
loc_registered varchar(255),
unknown_patient varchar(255),
gender varchar(50),
age_at_enc int,
address text,
ED_Visit_Start_Datetime datetime,
Triage_datetime datetime,
encounter_location text,
provider varchar(255),
Triage_queue_status varchar(255),
Triage_Color varchar(255),
Triage_Score int,
Chief_Complaint text,
Weight_KG double ,
Mobility text,
Respiratory_Rate double,
Blood_Oxygen_Saturation double,
Pulse double,
Systolic_Blood_Pressure double,
Diastolic_Blood_Pressure double,
Temperature_C double ,
Response text,
Trauma_Present text,
Neurological text,
Burn text,
Glucose text,
Trauma_type text,
Digestive text,
Pregnancy text,
Respiratory text,
Pain text,
Other_Symptom text,
Clinical_Impression text,
Pregnancy_Test text,
Glucose_Value double,
Paracetamol_dose double,
Treatment_Administered text,
Wait_Minutes double,
EDNote_encounter_id int(11),
EDNote_Datetime datetime,
EDNote_Disposition text,
ED_Diagnosis1 text,
ED_Diagnosis2 text,
ED_Diagnosis3 text,
ED_Diagnosis_noncoded text,
Consult_encounter_id int(11),
Consult_Datetime datetime,
Consult_Disposition text,
Cons_Diagnosis1 text,
Cons_Diagnosis2 text,
Cons_Diagnosis3 text,
Cons_Diagnosis_noncoded text
);
insert into temp_ED_Triage (patient_id, encounter_id, visit_id, Triage_datetime)
select e.patient_id, e.encounter_id, e.visit_id,e.encounter_datetime
from encounter e
where e.encounter_type = @EDTriageEnc and e.voided = 0
AND date(e.encounter_datetime) >=@startDate
AND date(e.encounter_datetime) <=@endDate
;
-- Dossier number
UPDATE temp_ED_Triage SET dossier_id = DOSID(patient_id);
-- zlemr_id
UPDATE temp_ED_Triage SET zlemr_id = ZLEMR(patient_id);
-- person address
UPDATE temp_ED_Triage SET address = PERSON_ADDRESS(patient_id);
-- Provider
UPDATE temp_ED_Triage SET provider = PROVIDER(encounter_id);
-- encounter location
UPDATE temp_ED_Triage SET encounter_location = ENCOUNTER_LOCATION_NAME(encounter_id);
-- gender
UPDATE temp_ED_Triage SET gender = GENDER(patient_id);
-- age at encounter
UPDATE temp_ED_Triage SET age_at_enc = age_at_enc(patient_id,encounter_id);
-- unknown patient
UPDATE temp_ED_Triage SET unknown_patient = unknown_patient(patient_id);
-- location registered
UPDATE temp_ED_Triage SET loc_registered = loc_registered(patient_id);
-- ED Visit Start Datetime
UPDATE temp_ED_Triage t
inner join visit v on t.visit_id = v.visit_id
set t.ED_Visit_Start_Datetime = v.date_started;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage queue status')
set t.Triage_queue_status = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage color classification')
set t.Triage_Color = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage score')
set t.Triage_Score = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('CIEL','160531')
set t.Chief_Complaint = o.value_text;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','WEIGHT (KG)')
set t.Weight_KG = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Mobility')
set t.Mobility = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','RESPIRATORY RATE')
set t.Respiratory_Rate = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','BLOOD OXYGEN SATURATION')
set t.Blood_Oxygen_Saturation = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','PULSE')
set t.Pulse = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','SYSTOLIC BLOOD PRESSURE')
set t.Systolic_Blood_Pressure = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','DIASTOLIC BLOOD PRESSURE')
set t.Diastolic_Blood_Pressure = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','TEMPERATURE (C)')
set t.Temperature_C = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Response triage symptom')
set t.Response = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
and o.value_coded = concept_from_mapping('PIH','Traumatic Injury')
set t.Trauma_Present = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Neurological triage symptom')
set t.Neurological = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Burn triage symptom')
set t.Burn = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Glucose triage symptom')
set t.Glucose = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Trauma triage symptom')
set t.Trauma_type = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Digestive triage symptom')
set t.Digestive = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','10721')
set t.Pregnancy = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Respiratory triage symptom')
set t.Respiratory = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Pain triage symptom')
set t.Pain = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Triage diagnosis')
inner join concept_set cs on cs.concept_id = o.value_coded and cs.concept_set = concept_from_mapping('PIH','Other triage symptom')
set t.Other_Symptom = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','CLINICAL IMPRESSION COMMENTS')
set t.Clinical_Impression = o.value_text;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','B-HCG')
set t.Pregnancy_Test = concept_name(o.value_coded,@locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','SERUM GLUCOSE')
set t.Glucose_Value = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Paracetamol dose (mg)')
set t.Paracetamol_dose = o.value_numeric;
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','3077')
set t.Wait_Minutes = round(o.value_numeric/60,0);
-- since treatment administered will be a list of obs potentially,
-- this is done with a grouped subquery
update temp_ED_Triage t
inner join
(select o.encounter_id, group_concat(concept_name(o.value_coded,@locale) separator ',') "treatments"
from obs o
where o.voided =0
and o.concept_id =concept_from_mapping('PIH','Emergency treatment')
group by o.encounter_id) et on et.encounter_id = t.encounter_id
set t.Treatment_Administered = et.treatments
;
-- The following statements gather information on the last consult (non-ED note) from the ED triage visit
update temp_ED_Triage t
set Consult_encounter_id = latestEncForminVisit(patient_id, @consEncName,visit_id, @consForm,null);
update temp_ED_Triage t
set Consult_Datetime = encounter_date(Consult_encounter_id);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.Consult_encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','HUM Disposition categories')
set t.Consult_Disposition = concept_name(o.value_coded,@locale);
update temp_ED_Triage
set Cons_Diagnosis1 = OBS_FROM_GROUP_ID_VALUE_CODED_LIST(OBS_ID(Consult_encounter_id, 'PIH', 'Visit Diagnoses', 0), 'CIEL', '1284', @locale);
update temp_ED_Triage
set Cons_Diagnosis2 = OBS_FROM_GROUP_ID_VALUE_CODED_LIST(OBS_ID(Consult_encounter_id, 'PIH', 'Visit Diagnoses', 1), 'CIEL', '1284', @locale);
update temp_ED_Triage
set Cons_Diagnosis3 = OBS_FROM_GROUP_ID_VALUE_CODED_LIST(OBS_ID(Consult_encounter_id, 'PIH', 'Visit Diagnoses', 2), 'CIEL', '1284', @locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.Consult_encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Diagnosis or problem, non-coded')
set t.ED_Diagnosis_noncoded = o.value_text;
-- The following statements gather information on the last ED note from the ED triage visit
update temp_ED_Triage t
set EDNote_encounter_id = latestEncForminVisit(patient_id, @consEncName,visit_id, @edNoteForm,null);
update temp_ED_Triage t
set EDNote_Datetime = encounter_date(EDNote_encounter_id);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.EDNote_encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','HUM Disposition categories')
set t.EDNote_Disposition = concept_name(o.value_coded,@locale);
update temp_ED_Triage
set ED_Diagnosis1 = OBS_FROM_GROUP_ID_VALUE_CODED_LIST(OBS_ID(EDNote_encounter_id, 'PIH', 'Visit Diagnoses', 0), 'CIEL', '1284', @locale);
update temp_ED_Triage
set ED_Diagnosis2 = OBS_FROM_GROUP_ID_VALUE_CODED_LIST(OBS_ID(EDNote_encounter_id, 'PIH', 'Visit Diagnoses', 1), 'CIEL', '1284', @locale);
update temp_ED_Triage
set ED_Diagnosis3 = OBS_FROM_GROUP_ID_VALUE_CODED_LIST(OBS_ID(EDNote_encounter_id, 'PIH', 'Visit Diagnoses', 2), 'CIEL', '1284', @locale);
update temp_ED_Triage t
inner join obs o on o.encounter_id = t.EDNote_encounter_id and o.voided =0
and o.concept_id =concept_from_mapping('PIH','Diagnosis or problem, non-coded')
set t.ED_Diagnosis_noncoded = o.value_text;
-- final output of data
Select
patient_id,
encounter_id,
visit_id,
zlemr_id,
dossier_id,
loc_registered,
unknown_patient,
gender,
age_at_enc,
address,
ED_Visit_Start_Datetime,
Triage_datetime,
encounter_location,
provider,
encounter_id,
Triage_queue_status,
Triage_Color,
Triage_Score,
Chief_Complaint,
Weight_KG,
Mobility,
Respiratory_Rate,
Blood_Oxygen_Saturation,
Pulse,
Systolic_Blood_Pressure,
Diastolic_Blood_Pressure,
Temperature_C,
Response,
Trauma_Present,
Neurological,
Burn,
Glucose,
Trauma_type,
Digestive,
Pregnancy,
Respiratory,
Pain,
Other_Symptom,
Clinical_Impression,
Pregnancy_Test,
Glucose_Value,
Paracetamol_dose,
Treatment_Administered,
Wait_Minutes,
EDNote_Datetime,
EDNote_Disposition,
ED_Diagnosis1,
ED_Diagnosis2,
ED_Diagnosis3,
ED_Diagnosis_noncoded,
Consult_Datetime,
Consult_Disposition,
Cons_Diagnosis1,
Cons_Diagnosis2,
Cons_Diagnosis3,
Cons_Diagnosis_noncoded
from temp_ED_Triage;
| true |
81d505f190d5191955c287a7f8c22177450a8641 | SQL | laomd-2/MySQL | /6/6.2.3.sql | UTF-8 | 464 | 3.25 | 3 | [] | no_license | DELIMITER //
CREATE PROCEDURE Proc_CalTotalPrice4Customer(p_custname CHAR(25))
BEGIN
DECLARE L_custkey INTEGER;
SELECT custkey INTO L_custkey FROM customer WHERE name=trim(p_custname);
UPDATE orders SET totalprice =
(SELECT SUM(extendedprice * (1-discount) * (1+tax))
FROM lineitem WHERE orders.orderkey=lineitem.orderkey
AND orders.custkey=L_custkey);
END//
CALL Proc_CalTotalPrice4Customer('Customer#000000100'); | true |
a58c0e41d29db06fcfbe8b3a25716d94a1586f4b | SQL | AnnaGashenko/franch | /franch.sql | UTF-8 | 20,781 | 2.890625 | 3 | [
"MIT"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.4.15.7
-- http://www.phpmyadmin.net
--
-- Хост: 127.0.0.1:3306
-- Время создания: Дек 09 2016 г., 10:53
-- Версия сервера: 5.5.50-log
-- Версия PHP: 5.4.45
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 */;
--
-- База данных: `franch`
--
-- --------------------------------------------------------
--
-- Структура таблицы `Achievs`
--
CREATE TABLE IF NOT EXISTS `Achievs` (
`AchievsID` int(11) NOT NULL,
`Mark` int(3) NOT NULL,
`Description` text NOT NULL,
`CategoryID` tinyint(4) NOT NULL,
`Icon` varchar(255) NOT NULL,
`StatusID` int(11) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `Achievs`
--
INSERT INTO `Achievs` (`AchievsID`, `Mark`, `Description`, `CategoryID`, `Icon`, `StatusID`) VALUES
(1, 100, 'Вы заполнили анкету курса', 1, '/skins/default/img/achievs/1_simply.png', NULL),
(2, 200, 'Вы выполнили 2 домашних работы вовремя и получили за них суммарно не менее 150 баллов.', 2, '/skins/default/img/achievs/2_bronze.png', 1),
(3, 300, 'Вы выполнили 5 домашних работ вовремя и получили за них суммарно не менее 350 баллов.', 2, '/skins/default/img/achievs/2_silver.png ', 2),
(4, 400, 'Вы выполнили 8 домашних работ вовремя и получили за них суммарно не менее 600 баллов.', 2, '/skins/default/img/achievs/2_gold.png', 3),
(5, 100, 'Вы полностью посмотрели 2 занятия онлайн или в записи.', 3, '/skins/default/img/achievs/3_bronze.png', 1),
(6, 200, 'Вы полностью посмотрели 5 занятий онлайн или в записи.', 3, '/skins/default/img/achievs/3_silver.png', 2),
(7, 300, 'Вы полностью посмотрели 8 занятий онлайн или в записи.', 3, '/skins/default/img/achievs/3_gold.png', 3),
(8, 100, 'Вы написали 20 осмысленных комментариев в чате занятий.', 4, '/skins/default/img/achievs/4_bronze.png', 1),
(9, 200, 'Вы написали 100 осмысленных комментариев в чате занятий.', 4, '/skins/default/img/achievs/4_silver.png', 2),
(10, 500, 'Вы написали 500 осмысленных комментариев в чате занятий.', 4, '/skins/default/img/achievs/4_gold.png', 3),
(11, 100, 'На заданный вами вопрос в прямом эфире ответили ведущие или спикеры курса. Достижения выдается за 2 таких вопроса. Учитываются как вопросы из зала, так и заданные в чате занятия.', 5, '/skins/default/img/achievs/5_bronze.png', 1),
(12, 300, 'На заданный вами вопрос в прямом эфире ответили ведущие или спикеры курса. Достижения выдается за 5 таких вопросов. Учитываются как вопросы из зала, так и заданные в чате занятия.', 5, '/skins/default/img/achievs/5_silver.png', 2),
(13, 500, 'На заданный вами вопрос в прямом эфире ответили ведущие или спикеры курса. Достижения выдается за 8 таких вопросов. Учитываются как вопросы из зала, так и заданные в чате занятия.', 5, '/skins/default/img/achievs/5_gold.png', 3),
(14, 200, 'По вашей ссылке на курсе зарегистрировалось минимум 2 человека (с любым пакетом участия), и этим человеком были не вы (мы проверяем)', 6, '/skins/default/img/achievs/6_bronze.png', 1),
(15, 1000, 'По вашей ссылке на курсе зарегистрировалось минимум 5 человек (с любым пакетом участия), и этим человеком были не вы (мы проверяем)', 6, '/skins/default/img/achievs/6_silver.png', 2),
(16, 2000, 'По вашей ссылке на курсе зарегистрировался 1 человек, который купил пакет VIP', 6, '/skins/default/img/achievs/6_gold.png', 3),
(17, 100, 'Вы поделились информацией о курсе в социальных сетях, где у вас более 50 друзей / подписчиков.', 7, '/skins/default/img/achievs/7_bronze.png', 1),
(18, 400, 'Вы поделились информацией о курсе в социальных сетях, где у вас более 500 друзей / подписчиков.', 7, '/skins/default/img/achievs/7_silver.png', 2),
(19, 800, 'Вы поделились информацией о курсе в социальных сетях, где у вас более 1000 друзей / подписчиков.', 7, '/skins/default/img/achievs/7_gold.png', 3),
(20, 200, 'Вы нашли 1 секретный код в занятии. Секретные коды отображаются на экране в зале и в онлайн-трансляции. Код представляет собой цифру в оранжевом круге.', 8, '/skins/default/img/achievs/8_bronze.png', 1),
(21, 600, 'Вы нашли 3 секретных кодов в занятиях. Секретные коды отображаются на экране в зале и в онлайн-трансляции. Код представляет собой цифру в оранжевом круге.', 8, '/skins/default/img/achievs/8_silver.png', 2),
(22, 1000, 'Вы нашли 5 секретных кодов в занятиях. Секретные коды отображаются на экране в зале и в онлайн-трансляции. Код представляет собой цифру в оранжевом круге.', 8, '/skins/default/img/achievs/8_gold.png', 3),
(23, 100, 'Вы оценили достижения троицы героев шоу в 2 занятиях, и поставили им рейтинги.', 9, '/skins/default/img/achievs/9_bronze.png', 1),
(24, 300, 'Вы оценили достижения троицы героев шоу в 5 занятиях, и поставили им рейтинги.', 9, '/skins/default/img/achievs/9_silver.png', 2),
(25, 500, 'Вы оценили достижения троицы героев шоу в 8 занятиях, и поставили им рейтинги.', 9, '/skins/default/img/achievs/9_gold.png', 3),
(26, 500, 'Вы купили пакет VIP. Теперь вы один из самых важных людей на курсе!', 11, '/skins/default/img/achievs/11_simply.png', NULL),
(27, 600, ' \nВы записали видеоотзыв об участии в курсе. Содержание видеоотзыва и ваша оценка не имеют значения. Даже если вам не понравился курс или отдельное занятие, но вы записали отзыв о нем, это также учитывается. Ссылку на видеоотзыв нужно прислать на адрес legend@franch.biz', 12, '/skins/default/img/achievs/12_simply.png', NULL),
(28, 1000, 'Ваш фаворит курса (один из троицы) выиграл в финале проекта (на 8-м занятии). Вашим фаворитом будет считаться тот, кому вы дали больше звезд.', 13, '/skins/default/img/achievs/13_simply.png', NULL),
(29, 200, 'Вы написали честные отзывы о том, что вам понравилось, и что нет на 2-х занятиях курса.', 14, '/skins/default/img/achievs/14_bronze.png', 1),
(30, 500, 'Вы написали честные отзывы о том, что вам понравилось, и что нет на 5-ти занятиях курса.', 14, '/skins/default/img/achievs/14_silver.png', 2),
(31, 1000, 'Вы написали честные отзывы о том, что вам понравилось, и что нет на 9-ти занятиях курса.', 14, '/skins/default/img/achievs/14_gold.png', 3),
(32, 2000, '<p>Воспользуйтесь любой услугой компании «Франч» со скидкой. <a href="http://franch.biz/aaa/franch-biz-myfranch-ru.pdf" target="_blank">Продвижение франшизы</a> (скидка для участников курса — 10%, VIP-участников — 20%). <a href="http://franch.biz/aaa/franch-2016.pdf" target="_blank">Создание франшизы</a> (скидка для участников курса — 5%, VIP-участников — 10%).</p>', 15, '/skins/default/img/achievs/15_simply.png', NULL),
(33, 500, 'Секретное достижение. Его условия вы узнаете после прохождения курса (8 занятий).', 16, '/skins/default/img/achievs/16_simply.png', NULL),
(34, 1000, 'Вы скачали все материалы курса и воспользовались всеми онлайн-сервисами.', 10, '/skins/default/img/achievs/10_simply.png', NULL);
-- --------------------------------------------------------
--
-- Структура таблицы `Category`
--
CREATE TABLE IF NOT EXISTS `Category` (
`CategoryID` int(11) NOT NULL,
`Name` varchar(25) NOT NULL,
`Description` text NOT NULL,
`Icon` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `Category`
--
INSERT INTO `Category` (`CategoryID`, `Name`, `Description`, `Icon`) VALUES
(1, 'Первое достижение', 'Вы заполнили анкету курса', '/skins/default/img/archievsDefault/1.png'),
(2, 'Прилежный ученик', 'Вы выполнили 2 домашних работы вовремя и получили за них суммарно не менее 150 баллов.', '/skins/default/img/archievsDefault/2.png'),
(3, 'Красные глаза', 'Вы полностью посмотрели 2 занятия онлайн или в записи.', '/skins/default/img/archievsDefault/3.png'),
(4, 'Разговорный жанр', 'Вы написали 20 осмысленных комментариев в чате занятий.', '/skins/default/img/archievsDefault/4.png'),
(5, 'Рука вверх', 'На заданный вами вопрос в прямом эфире ответили ведущие или спикеры курса. Достижения выдается за 2 таких вопроса. Учитываются как вопросы из зала, так и заданные в чате занятия.', '/skins/default/img/archievsDefault/5.png'),
(6, 'Приведи друга', 'По вашей ссылке на курсе зарегистрировалось минимум 2 человека (с любым пакетом участия), и этим человеком были не вы (мы проверяем)', '/skins/default/img/archievsDefault/6.png'),
(7, 'Социальная активность', 'Вы поделились информацией о курсе в социальных сетях, где у вас более 50 друзей / подписчиков.', '/skins/default/img/archievsDefault/7.png'),
(8, 'Секретные материалы', 'Вы нашли 1 секретный код в занятии. Секретные коды отображаются на экране в зале и в онлайн-трансляции. Код представляет собой цифру в оранжевом круге.', '/skins/default/img/archievsDefault/8.png'),
(9, 'Рождение Легенды', 'Вы оценили достижения троицы героев шоу в 2 занятиях, и поставили им рейтинги.', '/skins/default/img/archievsDefault/9.png'),
(10, 'Гигабайты знаний', 'Вы скачали все материалы курса и воспользовались всеми онлайн-сервисами.', '/skins/default/img/archievsDefault/10.png'),
(11, 'Важная персона', 'Вы купили пакет VIP. Теперь вы один из самых важных людей на курсе!', '/skins/default/img/archievsDefault/11.png'),
(12, 'Камера, мотор!', 'Вы записали видеоотзыв об участии в курсе. Содержание видеоотзыва и ваша оценка не имеют значения. Даже если вам не понравился курс или отдельное занятие, но вы записали отзыв о нем, это также учитывается. Ссылку на видеоотзыв нужно прислать на адрес legend@franch.biz', '/skins/default/img/archievsDefault/12.png'),
(13, 'Последний Герой', 'Ваш фаворит курса (один из троицы) выиграл в финале проекта (на 8-м занятии). Вашим фаворитом будет считаться тот, кому вы дали больше звезд.', '/skins/default/img/archievsDefault/13.png'),
(14, 'Критик Легенды', 'Вы написали честные отзывы о том, что вам понравилось, и что нет на 2-х занятиях курса.', '/skins/default/img/archievsDefault/14.png'),
(15, 'Дорогой клиент', '<p>Воспользуйтесь любой услугой компании «Франч» со скидкой. <a href="http://franch.biz/aaa/franch-biz-myfranch-ru.pdf" target="_blank">Продвижение франшизы</a> (скидка для участников курса — 10%, VIP-участников — 20%). <a href="http://franch.biz/aaa/franch-2016.pdf" target="_blank">Создание франшизы</a> (скидка для участников курса — 5%, VIP-участников — 10%).</p>', '/skins/default/img/archievsDefault/15.png'),
(16, 'Секретное достижение №3', 'Секретное достижение. Его условия вы узнаете после прохождения курса (8 занятий).', '/skins/default/img/archievsDefault/16.png');
-- --------------------------------------------------------
--
-- Структура таблицы `pages`
--
CREATE TABLE IF NOT EXISTS `pages` (
`id` int(11) NOT NULL,
`module` varchar(25) NOT NULL,
`static` tinyint(1) NOT NULL,
`meta_description` text NOT NULL,
`meta_keywords` text NOT NULL,
`meta_title` text NOT NULL,
`text` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `pages`
--
INSERT INTO `pages` (`id`, `module`, `static`, `meta_description`, `meta_keywords`, `meta_title`, `text`) VALUES
(1, '404', 1, 'Данная страница отсутствует', 'Данная страница отсутствует', 'Данная страница отсутствует', 'Данная страница отсутствует'),
(2, 'static', 0, '', '', '', ''),
(3, 'cab', 0, '', '', '', ''),
(4, 'errors', 0, '', '', '', ''),
(5, 'achievs', 0, '', '', '', '');
-- --------------------------------------------------------
--
-- Структура таблицы `StatusIcon`
--
CREATE TABLE IF NOT EXISTS `StatusIcon` (
`StatusID` int(11) NOT NULL,
`Name` varchar(25) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `StatusIcon`
--
INSERT INTO `StatusIcon` (`StatusID`, `Name`) VALUES
(1, 'бронза'),
(2, 'серебро'),
(3, 'золото');
-- --------------------------------------------------------
--
-- Структура таблицы `Users`
--
CREATE TABLE IF NOT EXISTS `Users` (
`UsersID` int(11) NOT NULL,
`Name` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`Password` char(13) NOT NULL,
`Country` varchar(25) DEFAULT NULL,
`City` varchar(25) DEFAULT NULL,
`Status` enum('Кто-то другой','Покупатель франшизы','Продавец франшизы') NOT NULL,
`Company` varchar(25) DEFAULT NULL,
`Format` enum('online','live') NOT NULL,
`Avatar` varchar(255) NOT NULL DEFAULT '/skins/default/img/avatars/default.jpg',
`date_registration` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `Users`
--
INSERT INTO `Users` (`UsersID`, `Name`, `Email`, `Password`, `Country`, `City`, `Status`, `Company`, `Format`, `Avatar`, `date_registration`) VALUES
(1, 'Test', 'user@test.test', 'CBGtE5HmzB/WU', 'Украина', 'Киев', 'Кто-то другой', NULL, 'online', '/skins/default/img/avatars/default.jpg', '2016-11-24 15:28:00'),
(2, 'Мария Перышкина', 'masha@gmail.com', 'CBkruLYz6k1UA', 'Украина', 'Киев', 'Кто-то другой', NULL, 'live', '/skins/default/img/avatars/default.jpg', '2016-11-25 16:07:18');
-- --------------------------------------------------------
--
-- Структура таблицы `UsersAchievs`
--
CREATE TABLE IF NOT EXISTS `UsersAchievs` (
`UsersID` int(11) NOT NULL,
`CategoryID` int(11) NOT NULL,
`AchievsID` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `UsersAchievs`
--
INSERT INTO `UsersAchievs` (`UsersID`, `CategoryID`, `AchievsID`) VALUES
(1, 1, 1),
(1, 2, 3),
(1, 5, 13),
(1, 7, 17),
(1, 13, 28);
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `Achievs`
--
ALTER TABLE `Achievs`
ADD PRIMARY KEY (`AchievsID`),
ADD KEY `StatusID` (`StatusID`);
--
-- Индексы таблицы `Category`
--
ALTER TABLE `Category`
ADD PRIMARY KEY (`CategoryID`);
--
-- Индексы таблицы `pages`
--
ALTER TABLE `pages`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `StatusIcon`
--
ALTER TABLE `StatusIcon`
ADD PRIMARY KEY (`StatusID`);
--
-- Индексы таблицы `Users`
--
ALTER TABLE `Users`
ADD PRIMARY KEY (`UsersID`),
ADD UNIQUE KEY `Email` (`Email`);
--
-- Индексы таблицы `UsersAchievs`
--
ALTER TABLE `UsersAchievs`
ADD PRIMARY KEY (`CategoryID`,`UsersID`),
ADD KEY `UsersID` (`UsersID`),
ADD KEY `CategoryID` (`CategoryID`),
ADD KEY `AchievsID` (`AchievsID`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `Achievs`
--
ALTER TABLE `Achievs`
MODIFY `AchievsID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=36;
--
-- AUTO_INCREMENT для таблицы `Category`
--
ALTER TABLE `Category`
MODIFY `CategoryID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=17;
--
-- AUTO_INCREMENT для таблицы `pages`
--
ALTER TABLE `pages`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT для таблицы `StatusIcon`
--
ALTER TABLE `StatusIcon`
MODIFY `StatusID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT для таблицы `Users`
--
ALTER TABLE `Users`
MODIFY `UsersID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
--
-- Ограничения внешнего ключа сохраненных таблиц
--
--
-- Ограничения внешнего ключа таблицы `UsersAchievs`
--
ALTER TABLE `UsersAchievs`
ADD CONSTRAINT `usersachievs_ibfk_3` FOREIGN KEY (`AchievsID`) REFERENCES `Achievs` (`AchievsID`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `usersachievs_ibfk_1` FOREIGN KEY (`UsersID`) REFERENCES `Users` (`UsersID`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `usersachievs_ibfk_2` FOREIGN KEY (`CategoryID`) REFERENCES `Category` (`CategoryID`) ON DELETE CASCADE ON UPDATE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
6aaaac6ab5f78058027e94359b98c163e0c1fe23 | SQL | ricots/awesome_praktikum_unikama | /UAS PRAKTIKUM PEMROGRAMAN 3/KELOMPOK 2/londry.sql | UTF-8 | 2,241 | 2.875 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 3.2.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Dec 16, 2016 at 02:55 PM
-- Server version: 5.1.41
-- PHP Version: 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: `londry`
--
-- --------------------------------------------------------
--
-- Table structure for table `detail_pembayaran`
--
CREATE TABLE IF NOT EXISTS `detail_pembayaran` (
`nonota` varchar(10) NOT NULL,
`kode` varchar(8) NOT NULL,
`harga` int(8) NOT NULL,
`jumlah` int(8) NOT NULL,
`subtotal` int(8) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `detail_pembayaran`
--
-- --------------------------------------------------------
--
-- Table structure for table `pembayaran`
--
CREATE TABLE IF NOT EXISTS `pembayaran` (
`nonota` varchar(8) NOT NULL,
`tanggal` date NOT NULL,
`total` int(8) NOT NULL,
PRIMARY KEY (`nonota`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `pembayaran`
--
-- --------------------------------------------------------
--
-- Table structure for table `tblbarang`
--
CREATE TABLE IF NOT EXISTS `tblbarang` (
`kode` varchar(10) NOT NULL,
`nama` varchar(30) NOT NULL,
`perkilo` int(10) NOT NULL,
`totalberat` int(10) NOT NULL,
`jumlah` int(5) NOT NULL,
PRIMARY KEY (`kode`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tblbarang`
--
-- --------------------------------------------------------
--
-- Table structure for table `tblsementara`
--
CREATE TABLE IF NOT EXISTS `tblsementara` (
`kode` varchar(30) NOT NULL,
`nama` varchar(30) NOT NULL,
`harga` int(8) NOT NULL,
`jumlah` int(8) NOT NULL,
`subtotal` int(8) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tblsementara`
--
/*!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 |
487f856b247d5d21fc335494ca9863b1f0c2166f | SQL | amartyaamp/corporate-political-nexus | /nexus/app/sql/28_mar/crawldb.sql | UTF-8 | 1,489 | 2.890625 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 28, 2016 at 05:26 PM
-- Server version: 5.5.41-0ubuntu0.14.04.1
-- PHP Version: 5.5.9-1ubuntu4.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `crawldb`
--
-- --------------------------------------------------------
--
-- Table structure for table `political_crawl_jan`
--
CREATE TABLE IF NOT EXISTS `political_crawl_jan` (
`id` int(11) DEFAULT NULL,
`mynetaid` varchar(20) DEFAULT NULL,
`name` varchar(50) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL,
`contact` varchar(15) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
`resolved` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `political_crawl_jan`
--
INSERT INTO `political_crawl_jan` (`id`, `mynetaid`, `name`, `email`, `contact`, `address`, `resolved`) VALUES
(1, '23', 'Naveen Jindal', 'something@someone.com', '55467878', 'Andhra etc', 0),
(2, '25', 'Narendra Modi', 'narendra@narendra.com', '8375956404', 'Gujarat', 0);
/*!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 |
6b6f9d1ca85ea7e114c6eeaed9df5e097deb7612 | SQL | Rutvij-dashputre/Rutvij-Edac2020 | /DBT(Assignment 5).sql | UTF-8 | 2,910 | 3.75 | 4 | [] | no_license | use assignment;
Create table EMP ( EMPNO numeric(4) not null, ENAME varchar(30) not null, JOB varchar(10), MGR numeric(4),
HIREDATE date, SAL numeric(7,2), DEPTNO numeric(2) );
Insert into EMP (EMPNO ,ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO ) values(1000, 'Manish' , 'SALESMAN', 1003,
'2020-02-18', 600, 30) ;
Insert into EMP (EMPNO ,ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO ) values(1001, 'Manoj' , 'SALESMAN', 1003,
'2018-02-18', 600, 30) ;
Insert into EMP (EMPNO ,ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO) values(1002 , 'Ashish', 'SALESMAN',1003 ,
'2013-02-18', 750, 30 );
Insert into EMP (EMPNO ,ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO ) values(1004, 'Rekha', 'ANALYST', 1006 ,
'2001-02-18', 3000, 10);
Insert into EMP (EMPNO ,ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO) values(1005 , 'Sachin', 'ANALYST', 1006 ,
'2019-02-18', 3000, 10 );
Insert into EMP (EMPNO ,ENAME, JOB, MGR, HIREDATE, SAL, DEPTNO ) values(1006, 'Pooja', 'MANAGER' ,
null , '2000-02-18' ,6000, 10 );
Create table dept (dno numeric(4) not null, dname varchar(10) not null,area varchar(30));
Insert into dept(dno,dname,area) values(10,'Store','Mumbai');
Insert into dept(dno,dname,area) values(20,'Purchase','Mumbai');
Insert into dept(dno,dname,area) values(30,'Store', 'Delhi');
Insert into dept(dno,dname,area) values(40,'Marketing','Pune');
Insert into dept(dno,dname,area) values(50,'Finance','Delhi');
Insert into dept(dno,dname,area) values(60,'Accounts','Mumbai');
delimiter $$
create procedure Que01(in val1 int, in val2 int)
Begin
select val1+val2;
select val1*val2;
select val1-val2;
select val1/val2;
end;$$
call Que01(20,10);
drop procedure Que01;
delimiter $$
create procedure Que02(inout str varchar(10))
begin
set str=(select reverse(str));
end $$
set @str='databse';
select @str;
call Que02(@str);
select @str as rev;
-- drop procedure Que02;
delimeter $$
create procedure Que03()
begin
select empno,ename,sal from emp order by sal desc limit 5;
end$$
delimiter $$
create procedure Que04()
begin
create table emp_test(e_id integer ,e_name varchar(20),e_joining_date date);
end $$
call Que04;
delimiter $$
create procedure Que05()
begin
insert into dept(deptno,dname,area) values (60,'education','pune');
end $$
select * from dept;
delimiter $$
create procedure Que06(in value int,out sqr int,out cu int)
begin
declare val1 int;
set sqr= power(val1,2);
set cu= power(val1,3);
end $$
call Que06(2,@sqr,@cu);
select @sqr;
select @cu;
-- drop procedure Que06;
delimiter $$
CREATE PROCEDURE Que07(OUT ANS INT)
BEGIN
DECLARE NUM int;
SET NUM=2;
SELECT NUM INTO ANS ;
END $$
CALL Que07(@ANS);
SELECT @ANS;
delimiter $$
create procedure Que08(in x int, out str varchar (50))
begin
select concat(e.ename , 'is from', d.dname) into str from emp e inner join dept d on d.dno=e.deptno where e.deptno=x and e.empno=1004;
end $$
call Que08(10,@str);
select @str;
| true |
2fbe7b81e48b238eb66619dd0af09df2bd4118a6 | SQL | NunoAlexandre/innovation-funding-service | /ifs-data-layer/ifs-data-service/src/main/resources/db/migration/V79_9_1__Add_affiliation.sql | UTF-8 | 847 | 3.375 | 3 | [
"MIT"
] | permissive | CREATE TABLE affiliation (
id BIGINT(20) PRIMARY KEY NOT NULL AUTO_INCREMENT,
user_id BIGINT(20) NOT NULL,
affiliation_type ENUM('EMPLOYER', 'PROFESSIONAL', 'PERSONAL', 'PERSONAL_FINANCIAL', 'FAMILY', 'FAMILY_FINANCIAL') NOT NULL,
affiliation_exists TINYINT(1) NOT NULL,
relation VARCHAR(255),
organisation VARCHAR(255),
position VARCHAR(255),
description VARCHAR(255),
created_by BIGINT(20) NOT NULL,
created_on DATETIME NOT NULL,
modified_on DATETIME NOT NULL,
modified_by BIGINT(20) NOT NULL,
CONSTRAINT affiliation_user_to_user_fk FOREIGN KEY (user_id) REFERENCES user (id),
CONSTRAINT affiliation_created_by_to_user_fk FOREIGN KEY (created_by) REFERENCES user (id),
CONSTRAINT affiliation_modified_by_to_user_fk FOREIGN KEY (modified_by) REFERENCES user (id)
) DEFAULT CHARSET=utf8; | true |
2084eee97788a69dfd4c3e16abdf662616d5a8cd | SQL | viniciustakedi/ExerciciosSenai_2S-2020 | /banco de dados/Arquivos SQL/exe_Pessoas.sql | ISO-8859-1 | 1,829 | 4 | 4 | [] | no_license | CREATE DATABASE exe_pessoas
USE exe_pessoas
--Criar tabela
CREATE TABLE Pessoas (
IdPessoas INT PRIMARY KEY IDENTITY,
Nome VARCHAR (200)
);
CREATE TABLE Email (
IdUsuario INT PRIMARY KEY IDENTITY,
Descricao VARCHAR (200),
IdPessoas INT FOREIGN KEY REFERENCES Pessoas (IdPessoas)
);
CREATE TABLE Telefones (
IdTelefone INT PRIMARY KEY IDENTITY,
Descricao VARCHAR (200),
Numero INT,
IdPessoas INT FOREIGN KEY REFERENCES Pessoas (IdPessoas)
);
CREATE TABLE Cnh (
IdCnh INT PRIMARY KEY IDENTITY,
Descricao VARCHAR (200),
IdPessoas INT FOREIGN KEY REFERENCES Pessoas (IdPessoas)
);
--Fim da criao de tabela
--Comeo DML LINGUAGEM DE MANIPULAO DE DADOS
INSERT INTO Pessoas (Nome)
VALUES ('Rafaela'), ('Aline'), ('Denilson'), ('Gabriela'), ('Jamelo'), ('Gary');
INSERT INTO Email (IdPessoas, Descricao)
VALUES (3, 'Deni@gmail.com'), (1, 'Rafinha@yahoo.com'), (2, 'Ventilador@bol.com.br'), (4, 'bibizinha322@gmail.com'), (5, 'saidarua@jamelao.net'), (6, 'mooncake@gmail.com');
INSERT INTO Telefones (IdPessoas, Numero)
VALUES (1, 119343-9938), (2, 112873-9874), (3, 119873-7733), (4, 118765-7633), (5, 118736-9082), (6, 119873-7663);
INSERT INTO Cnh (IdPessoas, Descricao)
VALUES (1, 'S: 33129-3'),(2, 'S: 33431-0'),(3, 'S: 32344-1'),(4, 'S: 93293-1'),(6, 'S: 38218-9');
UPDATE Telefones --Mudar o telefone de uma pessoa especifica
SET Numero = '27865833'
WHERE IdPessoas = 6
INSERT INTO Email (IdPessoas, Descricao) --Adicionar um email a uma pessoa especifica
VALUES (1, 'rafa@gmail.com');
DELETE FROM Pessoas
WHERE IdPessoas = 5
--FIM DML
--Comeo DQL
SELECT * FROM Pessoas
SELECT * FROM Email
SELECT * FROM Telefones
SELECT * FROM Cnh
SELECT Descricao FROM Email WHERE IdPessoas = 1 ; --Selecionar todos os emails de uma pessoa especifica
SELECT Numero FROM Telefones WHERE IdPessoas = 1 ; -- Todos os telefones
SELECT * FROM CNH
--FIM DQL | true |
663c527b7854465f1a424bd1dbe7a6159072e356 | SQL | marcusgram/7381792102112121 | /administration/storage/tablespaces/undo/UNDO_corruption.sql | UTF-8 | 2,275 | 3.375 | 3 | [] | no_license |
Unable to drop undo tablespace due to ORA-01548: active rollback segment
------------------------------------------------------------------------
Problem:
– create a new undo tablespace and set it to undo tablespace of instance
sys@ora11gr2> alter system set undo_tablespace=undotbs2;
– but we can not drop the original one
sys@ora11gr2> drop tablespace undotbs1 including contents and datafiles;
drop tablespace undotbs1 including contents and datafiles
*
ERROR at line 1:
ORA-01548: active rollback segment ‘_SYSSMU2_6654314$’ found, terminate dropping tablespace
Cause of the problem
An attempt was made to drop a tablespace that contains active rollback segments
Solution:
1) find all active rollback segment in the undo tablespace to be dropped.
sys@ora11gr2> select segment_name, tablespace_name, status from dba_rollback_segs where tablespace_name=’UNDOTBS1'
SEGMENT_NAME TABLESPACE_NAME STATUS
—————————— —————————— —————-
_SYSSMU10_820739558$ UNDOTBS1 OFFLINE
_SYSSMU9_2448906239$ UNDOTBS1 OFFLINE
_SYSSMU8_3066916762$ UNDOTBS1 OFFLINE
_SYSSMU7_892861194$ UNDOTBS1 OFFLINE
_SYSSMU6_1956589931$ UNDOTBS1 OFFLINE
_SYSSMU5_2919322705$ UNDOTBS1 OFFLINE
_SYSSMU4_3876247569$ UNDOTBS1 OFFLINE
_SYSSMU3_4245574747$ UNDOTBS1 OFFLINE
_SYSSMU2_6654314$ UNDOTBS1 PARTLY AVAILABLE
2) set a parameter including all active rollback segments in init.ora file
create pfile='/tmp/rescue.ora' from spfile;
_offline_rollback_segments=(_SYSSMU2_6654314$,…..)
3) shutdown database
4) Mount the database using pfile
sys@ora11gr2> startup mount pfile='/tmp/rescue.ora'
5) offline undo datafile for drop
sys@ora11gr2> alter database datafile ‘/app/oracle/oradata/ORA11GR2/undotbs1.dbf’ offline drop;
6) open database
sys@ora11gr2> alter database open;
7)drop the undo segment
sys@ora11gr2> drop rollback segment “_SYSSMU2_6654314$”;
8)Add a new undo tablespace and set it as instance’s undo tablespace
…
sys@ora11gr2> alter system set undo_tablespace=undotbs2;
9) drop original undo tablespace
sql>Drop Tablespace undotbs1 including contents and datafiles;
10) remove the _offline_rollback_segments parameter fron pfile
| true |
1b9e7035a31e8cc33d6ebdfe2a4152b078a332e7 | SQL | meldig/SQL | /schema/structure commune/suppression_structure_commune.sql | UTF-8 | 2,488 | 2.890625 | 3 | [] | no_license | /*
Suppression de la structure du schéma G_GEO (tables, déclencheurs, vues, indexes, métadonnées spatiales)
*/
-- 1. Suppression des tables pivots
DROP TABLE G_GEO.TA_FAMILLE_LIBELLE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_LIBELLE_RELATION CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_LIBELLE_CORRESPONDANCE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_IDENTIFIANT_COMMUNE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_IDENTIFIANT_ZONE_ADMINISTRATIVE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_METADONNEE_RELATION_ORGANISME CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_METADONNEE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_ZA_COMMUNES CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_BPE_RELATION_GEOM CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_BPE_CARACTERISTIQUE_QUANTITATIVE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_BPE_CARACTERISTIQUE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_BPE_RELATION_CODE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_GG_POINT_VIGILANCE_PERMIS_CONSTRUIRE CASCADE CONSTRAINTS;
-- 2. Supression des tables contenants des clés étrangères
DROP TABLE G_GEO.TA_CODE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_ZONE_ADMINISTRATIVE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_COMMUNE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_LIBELLE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_BPE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_IRIS CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_GG_POINT_VIGILANCE_AUDIT CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_GG_POINT_VIGILANCE CASCADE CONSTRAINTS;
-- 3. Suppression des tables ne contenant aucune clé étrangère
DROP TABLE G_GEO.TA_FAMILLE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_NOM CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_LIBELLE_LONG CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_LIBELLE_COURT CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_ORGANISME CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_SOURCE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_DATE_ACQUISITION CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_ECHELLE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_PROVENANCE CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_BPE_GEOM CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_IRIS_GEOM CASCADE CONSTRAINTS;
DROP TABLE G_GEO.TA_GG_PERMIS_CONSTRUIRE CASCADE CONSTRAINTS;
-- 4. Suppression des métadonnées spatiales
DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = 'TA_COMMUNE';
DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = 'TA_BPE_GEOM';
DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = 'TA_IRIS_GEOM';
DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = 'TA_GG_POINT_VIGILANCE';
COMMIT; | true |
9e2cdb7b0368070c02793a0ea9641414c7d0260d | SQL | SmarterApp/AP_ItemAuthoring | /sbac-iaip-rpm-installer/iaip-tomcatjasper-rpm/src/main/opt/jasper-update/buildomatic/install_resources/sql/oracle/quartz.ddl | UTF-8 | 9,176 | 3.34375 | 3 | [
"Apache-2.0"
] | permissive | -- Comments from the original Oracle Quartz file:
--
-- A hint submitted by a user: Oracle DB MUST be created as "shared" and the
-- job_queue_processes parameter must be greater than 2, otherwise a DB lock
-- will happen. However, these settings are pretty much standard after any
-- Oracle install, so most users need not worry about this.
--
-- Many other users (including the primary author of Quartz) have had success
-- runing in dedicated mode, so only consider the above as a hint ;-)
--
-- Comments from Jaspersoft:
--
--
-- 2012-05-23: tkavanagh:
-- In the switch from quartz 1.5 to 2.1.2, we have to handle the
-- table and column size changes carefully because of existing
-- JRS customers who will be upgrading from older JRS (and thus
-- older quartz). If column sizes were made larger in quartz
-- 2.1.2, we are ignoring this and leaving the col size the same.
-- So, for instance, if qrtz_job_details.JOB_NAME was increased
-- to (200) in 2.1.2, I explicitly set it to (80) which is what it
-- was in quartz 1.5.
-- Additional, specific changes for Oracle:
-- - qrtz_simple_triggers.times_triggered is set to number(7)
-- This is the value used in quartz 1.5.
--
-- 2012-01-24: thorick chow:
-- I'll follow Tony's lead with this version for Quartz 2.1.2
-- and comment out the drop table statements
--
-- 2008-04-17: tkavanagh:
-- Commented out the drop table statements because they
-- cause the repository-hibernate/build-db step to fail
--
-- delete from qrtz_fired_triggers;
-- delete from qrtz_simple_triggers;
-- delete from qrtz_simprop_triggers;
-- delete from qrtz_cron_triggers;
-- delete from qrtz_blob_triggers;
-- delete from qrtz_triggers;
-- delete from qrtz_job_details;
-- delete from qrtz_calendars;
-- delete from qrtz_paused_trigger_grps;
-- delete from qrtz_locks;
-- delete from qrtz_scheduler_state;
-- drop table qrtz_calendars;
-- drop table qrtz_fired_triggers;
-- drop table qrtz_blob_triggers;
-- drop table qrtz_cron_triggers;
-- drop table qrtz_simple_triggers;
-- drop table qrtz_simprop_triggers;
-- drop table qrtz_triggers;
-- drop table qrtz_job_details;
-- drop table qrtz_paused_trigger_grps;
-- drop table qrtz_locks;
-- drop table qrtz_scheduler_state;
CREATE TABLE qrtz_job_details
(
SCHED_NAME VARCHAR(100) NOT NULL,
JOB_NAME VARCHAR2(80) NOT NULL,
JOB_GROUP VARCHAR2(80) NOT NULL,
DESCRIPTION VARCHAR2(120) NULL,
JOB_CLASS_NAME VARCHAR2(128) NOT NULL,
IS_DURABLE VARCHAR2(1) NOT NULL,
IS_NONCONCURRENT VARCHAR2(1) NOT NULL,
IS_UPDATE_DATA VARCHAR2(1) NOT NULL,
REQUESTS_RECOVERY VARCHAR2(1) NOT NULL,
JOB_DATA BLOB NULL,
CONSTRAINT qrtz_job_details_pkey PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
);
CREATE TABLE qrtz_triggers
(
SCHED_NAME VARCHAR(100) NOT NULL,
TRIGGER_NAME VARCHAR2(80) NOT NULL,
TRIGGER_GROUP VARCHAR2(80) NOT NULL,
JOB_NAME VARCHAR2(80) NOT NULL,
JOB_GROUP VARCHAR2(80) NOT NULL,
DESCRIPTION VARCHAR2(120) NULL,
NEXT_FIRE_TIME NUMBER(13) NULL,
PREV_FIRE_TIME NUMBER(13) NULL,
PRIORITY NUMBER(13) NULL,
TRIGGER_STATE VARCHAR2(16) NOT NULL,
TRIGGER_TYPE VARCHAR2(8) NOT NULL,
START_TIME NUMBER(13) NOT NULL,
END_TIME NUMBER(13) NULL,
CALENDAR_NAME VARCHAR2(80) NULL,
MISFIRE_INSTR NUMBER(2) NULL,
JOB_DATA BLOB NULL,
CONSTRAINT qrtz_triggers_pkey PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
CONSTRAINT qrtz_triggers_fkey FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)
);
CREATE TABLE qrtz_simple_triggers
(
SCHED_NAME VARCHAR(100) NOT NULL,
TRIGGER_NAME VARCHAR2(80) NOT NULL,
TRIGGER_GROUP VARCHAR2(80) NOT NULL,
REPEAT_COUNT NUMBER(7) NOT NULL,
REPEAT_INTERVAL NUMBER(12) NOT NULL,
TIMES_TRIGGERED NUMBER(7) NOT NULL,
CONSTRAINT qrtz_simple_triggers_pkey PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
CONSTRAINT qrtz_simple_triggers_fkey FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_cron_triggers
(
SCHED_NAME VARCHAR(100) NOT NULL,
TRIGGER_NAME VARCHAR2(80) NOT NULL,
TRIGGER_GROUP VARCHAR2(80) NOT NULL,
CRON_EXPRESSION VARCHAR2(80) NOT NULL,
TIME_ZONE_ID VARCHAR2(80),
CONSTRAINT qrtz_cron_triggers_pkey PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
CONSTRAINT qrtz_cron_triggers_fkey FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_simprop_triggers
(
SCHED_NAME VARCHAR(100) NOT NULL,
TRIGGER_NAME VARCHAR(80) NOT NULL,
TRIGGER_GROUP VARCHAR(80) NOT NULL,
STR_PROP_1 VARCHAR(512) NULL,
STR_PROP_2 VARCHAR(512) NULL,
STR_PROP_3 VARCHAR(512) NULL,
INT_PROP_1 INT NULL,
INT_PROP_2 INT NULL,
LONG_PROP_1 NUMBER(19) NULL,
LONG_PROP_2 NUMBER(19) NULL,
DEC_PROP_1 NUMERIC(13,4) NULL,
DEC_PROP_2 NUMERIC(13,4) NULL,
BOOL_PROP_1 VARCHAR(1) NULL,
BOOL_PROP_2 VARCHAR(1) NULL,
CONSTRAINT qrtz_simprop_triggers_pkey PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
CONSTRAINT qrtz_simprop_triggers_fkey FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_blob_triggers
(
SCHED_NAME VARCHAR(100) NOT NULL,
TRIGGER_NAME VARCHAR2(80) NOT NULL,
TRIGGER_GROUP VARCHAR2(80) NOT NULL,
BLOB_DATA BLOB NULL,
CONSTRAINT qrtz_blob_triggers_pkey PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
CONSTRAINT qrtz_blob_triggers_fkey FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_calendars
(
SCHED_NAME VARCHAR(100) NOT NULL,
CALENDAR_NAME VARCHAR2(80) NOT NULL,
CALENDAR BLOB NOT NULL,
CONSTRAINT qrtz_calendars_pkey PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)
);
CREATE TABLE qrtz_paused_trigger_grps
(
SCHED_NAME VARCHAR(100) NOT NULL,
TRIGGER_GROUP VARCHAR2(80) NOT NULL,
CONSTRAINT qrtz_paused_trigger_grps_pkey PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_fired_triggers
(
SCHED_NAME VARCHAR(100) NOT NULL,
ENTRY_ID VARCHAR2(95) NOT NULL,
TRIGGER_NAME VARCHAR2(80) NOT NULL,
TRIGGER_GROUP VARCHAR2(80) NOT NULL,
INSTANCE_NAME VARCHAR2(80) NOT NULL,
FIRED_TIME NUMBER(13) NOT NULL,
PRIORITY NUMBER(13) NOT NULL,
STATE VARCHAR2(16) NOT NULL,
JOB_NAME VARCHAR2(80) NULL,
JOB_GROUP VARCHAR2(80) NULL,
IS_NONCONCURRENT VARCHAR2(1) NULL,
REQUESTS_RECOVERY VARCHAR2(1) NULL,
CONSTRAINT qrtz_fired_triggers_pkey PRIMARY KEY (SCHED_NAME,ENTRY_ID)
);
CREATE TABLE qrtz_scheduler_state
(
SCHED_NAME VARCHAR(100) NOT NULL,
INSTANCE_NAME VARCHAR2(80) NOT NULL,
LAST_CHECKIN_TIME NUMBER(13) NOT NULL,
CHECKIN_INTERVAL NUMBER(13) NOT NULL,
CONSTRAINT qrtz_scheduler_state_pkey PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)
);
CREATE TABLE qrtz_locks
(
SCHED_NAME VARCHAR(100) NOT NULL,
LOCK_NAME VARCHAR2(40) NOT NULL,
CONSTRAINT qrtz_locks_pkey PRIMARY KEY (SCHED_NAME,LOCK_NAME)
);
CREATE INDEX idx_qrtz_j_req_recovery on qrtz_job_details(SCHED_NAME,REQUESTS_RECOVERY);
CREATE INDEX idx_qrtz_j_grp on qrtz_job_details(SCHED_NAME,JOB_GROUP);
CREATE INDEX idx_qrtz_t_j on qrtz_triggers(SCHED_NAME,JOB_NAME,JOB_GROUP);
CREATE INDEX idx_qrtz_t_jg on qrtz_triggers(SCHED_NAME,JOB_GROUP);
CREATE INDEX idx_qrtz_t_c on qrtz_triggers(SCHED_NAME,CALENDAR_NAME);
CREATE INDEX idx_qrtz_t_g on qrtz_triggers(SCHED_NAME,TRIGGER_GROUP);
CREATE INDEX idx_qrtz_t_state on qrtz_triggers(SCHED_NAME,TRIGGER_STATE);
CREATE INDEX idx_qrtz_t_n_state on qrtz_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX idx_qrtz_t_n_g_state on qrtz_triggers(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX idx_qrtz_t_next_fire_time on qrtz_triggers(SCHED_NAME,NEXT_FIRE_TIME);
CREATE INDEX idx_qrtz_t_nft_st on qrtz_triggers(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME);
CREATE INDEX idx_qrtz_t_nft_misfire on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME);
CREATE INDEX idx_qrtz_t_nft_st_misfire on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
CREATE INDEX idx_qrtz_t_nft_st_misfire_grp on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX idx_qrtz_ft_trig_inst_name on qrtz_fired_triggers(SCHED_NAME,INSTANCE_NAME);
CREATE INDEX idx_qrtz_ft_inst_job_req_rcvry on qrtz_fired_triggers(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY);
CREATE INDEX idx_qrtz_ft_j_g on qrtz_fired_triggers(SCHED_NAME,JOB_NAME,JOB_GROUP);
CREATE INDEX idx_qrtz_ft_jg on qrtz_fired_triggers(SCHED_NAME,JOB_GROUP);
CREATE INDEX idx_qrtz_ft_t_g on qrtz_fired_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP);
CREATE INDEX idx_qrtz_ft_tg on qrtz_fired_triggers(SCHED_NAME,TRIGGER_GROUP);
COMMIT;
| true |
38289e378c1c701e663741dcac35f80b9b77cf76 | SQL | solaresjuan98/bd1-proyecto1 | /util/substring.sql | UTF-8 | 555 | 3.171875 | 3 | [] | no_license | SELECT REGEXP_SUBSTR('Hello world !', '[^ ]+', 1, 1) as palabra_1
, REGEXP_SUBSTR('Hello world !', '[^ ]+', 1, 2) as palabra_2
, REGEXP_SUBSTR('Hello world !', '[^ ]+', 1, 3) as palabra_3
FROM DUAL;
SELECT REGEXP_SUBSTR('Hello world !', '[^ ]+', 1, 1) as palabra_1
FROM DUAL;
SELECT (SELECT REGEXP_SUBSTR(CLIENT_NAME, '[^ ]+', 1, 1)
FROM DUAL) AS NOMBRE,
(SELECT REGEXP_SUBSTR(CLIENT_NAME, '[^ ]+', 1, 2)
FROM DUAL) AS APELLIDO
FROM CLIENT;
-- specific subrstring in a string
select INSTR('sonso', 'son') as subcadena
from dual;
| true |
6ebf7506ac4c7b494fc5a487d57907ae1da12ce9 | SQL | Alirasheed94/FinalWeek8 | /db/register.sql | UTF-8 | 1,718 | 2.84375 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.3.11
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Feb 09, 2020 at 10:13 AM
-- Server version: 5.6.24
-- PHP Version: 5.6.8
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `busmanagementsystem`
--
-- --------------------------------------------------------
--
-- Table structure for table `register`
--
CREATE TABLE IF NOT EXISTS `register` (
`userid` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`confirmPassword` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`confirmEmail` varchar(50) NOT NULL,
`firstName` varchar(50) NOT NULL,
`lastName` varchar(50) NOT NULL,
`mobile` varchar(50) NOT NULL,
`address` varchar(50) NOT NULL,
`dob` varchar(50) NOT NULL,
`gender` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `register`
--
INSERT INTO `register` (`userid`, `password`, `confirmPassword`, `email`, `confirmEmail`, `firstName`, `lastName`, `mobile`, `address`, `dob`, `gender`) VALUES
('rafay', 'rafay', 'rafay', 'rafay', '2013', 'January', '1', '0320', 'rafay', 'rafay', 'Male');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `register`
--
ALTER TABLE `register`
ADD PRIMARY KEY (`userid`);
/*!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 |
a080fbfc37cbb9c6eb9b84920e860a54f5952da1 | SQL | gicadmin/allo | /PHENIX/Tables/CUSTOMER_ADJUSTMENT_CONSIGNS.sql | UTF-8 | 2,093 | 3.546875 | 4 | [] | no_license | CREATE TABLE phenix.customer_adjustment_consigns (
cac_cad_id NUMBER(15) NOT NULL,
cac_sequence NUMBER(2) NOT NULL,
cac_prf_prd_code VARCHAR2(10 BYTE) NOT NULL,
cac_prf_fmt_code VARCHAR2(7 BYTE) NOT NULL,
cac_cost_price NUMBER(7,2) NOT NULL,
cac_quantity NUMBER(7) NOT NULL,
cac_selling_price NUMBER(7,2) NOT NULL,
cac_federal_tax_rate NUMBER(6,3) DEFAULT 0 NOT NULL,
cac_provincial_tax_rate NUMBER(6,3) DEFAULT 0 NOT NULL,
cac_invoiced_ext_price NUMBER(10,2) DEFAULT 0 NOT NULL,
CONSTRAINT cac_pk PRIMARY KEY (cac_cad_id,cac_sequence),
CONSTRAINT cac_cad_fk FOREIGN KEY (cac_cad_id) REFERENCES phenix.customer_adjustment_details (cad_id) ON DELETE CASCADE,
CONSTRAINT cac_prf_fk FOREIGN KEY (cac_prf_prd_code,cac_prf_fmt_code) REFERENCES phenix.product_formats (prf_prd_code,prf_fmt_code)
);
COMMENT ON TABLE phenix.customer_adjustment_consigns IS 'Cette table contient les détails de consignes associé au produit';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_cad_id IS 'Identifiant unique des détails';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_sequence IS 'Numéro préservant la séquence des consignes';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_prf_prd_code IS 'Numéro du produit';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_prf_fmt_code IS 'Numéro du format';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_cost_price IS 'Prix du coûtant';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_quantity IS 'Quantité de la consigne';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_selling_price IS 'Prix de vente';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_federal_tax_rate IS 'Indique le taux de taxe fédérale appliqué ';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_provincial_tax_rate IS 'Indique le taux de taxe provinciale appliqué ';
COMMENT ON COLUMN phenix.customer_adjustment_consigns.cac_invoiced_ext_price IS 'Indique le montant facturé à la ligne, qté * prix vendant, arrondi toujours vers le haut, à deux décimales'; | true |
2e70388f094697d6de966a9f43b6f9e04687808b | SQL | gustavoper/SocExames | /sql/ddl.sql | UTF-8 | 851 | 2.828125 | 3 | [] | no_license | create table exame
(
id mediumint(8) unsigned not null primary key auto_increment,
id_paciente mediumint(8) unsigned not null,
id_medico mediumint(8) unsigned not null,
id_tipo_exame mediumint(8) unsigned not null,
email_paciente varchar(255) not null,
observacao_exame text null,
id_externo_exame varchar(200) not null
);
create table medico
(
id mediumint(8) unsigned not null primary key auto_increment,
nome varchar(255) not null,
ativo tinyint(1) unsigned not null default 1
);
create table paciente
(
id mediumint(8) unsigned not null primary key auto_increment,
nome varchar(255) not null,
ativo tinyint(1) unsigned not null default 1
);
create table tipoExame
(
id mediumint(8) unsigned not null primary key auto_increment,
nome varchar(200) not null,
ativo tinyint(1) unsigned not null default 1
); | true |
f158055f00e2c5f4b14b75c0bf50ac8409e2ca57 | SQL | kasyJ/taskphp | /migrations/001_add_task.sql | UTF-8 | 449 | 2.734375 | 3 | [] | no_license | -- Таблица задач --
-- имена таблиц и полей в бэквотак или без них, ни каких кавычек!
CREATE TABLE `tasks` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`text` TEXT NOT NULL,
`completed` BOOLEAN DEFAULT FALSE,
`edited` BOOLEAN DEFAULT FALSE,
PRIMARY KEY (id)
)
CHARACTER SET utf8mb4
COLLATE utf8mb4_general_ci; | true |
5b067287ee035e7e8aea4892544365d8403166a3 | SQL | diegombt/ss-dba-queries | /reports/ss-tables_in_filegroups.sql | UTF-8 | 1,066 | 3.984375 | 4 | [] | no_license | ------------------------------------------------------------------------------------------------------------
-- List of Table in Filegroup with table size in SQL Server
-- Know list of table under each file group along with size of that table and name of clustered index if any
-- http://blog.extreme-advice.com/2013/01/17/list-of-table-in-filegroup-with-table-size-in-sql-server/
------------------------------------------------------------------------------------------------------------
SELECT filegroup_name(au.data_space_id) as FileGroupName
,object_name(Parti.object_id) as TableName
,ind.name as ClusteredIndexName
,au.total_pages/128 as TotalTableSizeInMB
,au.used_pages/128 as UsedSizeInMB
,au.data_pages/128 as DataSizeInMB
from sys.allocation_units au
join sys.partitions Parti
on au.container_id =
case when au.type in(1, 3)
then Parti.hobt_id
else Parti.partition_id end
left join sys.indexes ind
on ind.object_id = Parti.object_id
and ind.index_id = Parti.index_id
order by 1, 4 desc | true |
ed7a62932e75f76461f4486b3a00abe131c42706 | SQL | CostanCatalin/KiMo | /plsql/pachet_functii_membri.sql | UTF-8 | 5,246 | 4.0625 | 4 | [] | no_license |
create or replace package children_functions as
TYPE age_distribution IS VARRAY(20) of float;
function getAge (child_id in kids_kid.id%type) return number;
function getAgeDistribution(year in integer) return float;
function getChildrenInThatMonth(month in integer) return number;
function getDistance(x1 in float, y1 in float, x2 in float, y2 in float) return float;
function getDistanceBetweenKids(p_x in float, p_y in float, p_kid_id in kids_kid.id%type) return float;
procedure checkNeighbours(p_kid_id in kids_kid.id%type, distance in integer, p_x in float, p_y in float);
end children_functions;
/
create or replace package body children_functions as
function getAge
(child_id in kids_kid.id%type)
return number as
age number := 0;
begin
select
floor((current_date - birth_date)/365.25)
into age from kids_kid where id = child_id;
return age;
end getAge;
function getAgeDistribution
(year in integer)
return float is
CURSOR children_cur IS
SELECT *
FROM kids_kid
ORDER BY id ASC;
distribution children_functions.age_distribution;
current_age integer;
total integer := 0;
counter integer := 0;
begin
FOR children_rec IN children_cur loop
current_age := getAge(children_rec.id);
if (current_age = year) then
counter := counter + 1;
end if;
total := total + 1;
end loop;
return (counter / total) * 100;
end getAgeDistribution;
function getChildrenInThatMonth(month in integer)
return number is
counter integer := 0;
begin
SELECT count(*) into counter
FROM kids_kid
Where month = extract(month from registered_date)
and extract(year from registered_date) = extract(year from current_date)
ORDER BY id ASC;
return counter;
end getChildrenInThatMonth;
function getDistance(x1 in float, y1 in float, x2 in float, y2 in float)
return float is
v_return float;
v_delta1 float;
v_delta2 float;
v_lat_sin float;
v_lng_sin float;
v_tmp float;
begin
v_delta1 := x2 - x1;
v_delta2 := y2 - y1;
v_lat_sin := sin(v_delta1 / 2.0);
v_lng_sin := sin(v_delta2 / 2.0);
v_tmp := power(v_lat_sin, 2) + cos(x1) * cos(x2) * power(v_lng_sin, 2);
v_return := 2 * asin(sqrt(v_tmp));
return v_return * 6371000;
end getDistance;
function getDistanceBetweenKids(p_x in float, p_y in float, p_kid_id in kids_kid.id%type)
return float is
x2 float;
y2 float;
PRAGMA AUTONOMOUS_TRANSACTION;
begin
select latitude, longitude into x2, y2 from
(select latitude, longitude from kids_location where kid_id = p_kid_id order by date_created desc)
where rownum = 1;
return getDistance(p_x, p_y, x2, y2);
EXCEPTION WHEN OTHERS THEN
return -1;
end getDistanceBetweenKids;
procedure checkNeighbours(p_kid_id in kids_kid.id%type, distance in integer, p_x in float, p_y in float) is
v_last_x1 float;
v_last_y1 float;
v_last_x2 float;
v_last_y2 float;
v_distance float;
-- PRAGMA AUTONOMOUS_TRANSACTION;
begin
for i in (select id from kids_kid where id <> p_kid_id) loop
v_distance := getDistanceBetweenKids(p_x, p_y, i.id);
if (v_distance <= distance and v_distance >= 0) then
begin
select latitude, longitude into v_last_x1, v_last_y1 from (Select latitude, longitude, rownum as rn from(Select * from kids_location k where k.kid_id = p_kid_id order by k.date_created desc))
where rn=1;
select latitude, longitude into v_last_x2, v_last_y2 from (Select latitude, longitude, rownum as rn from(Select * from kids_location k where k.kid_id = i.id order by k.date_created desc))
where rn=2;
if ((getDistance(v_last_x1, v_last_y1, v_last_x2, v_last_y2) > distance)) then
insert into kids_encounter
(date_created, kid_1_id, kid_2_id)
values (sysdate, p_kid_id, i.id);
commit;
return;
end if;
EXCEPTION WHEN NO_DATA_FOUND THEN
insert into kids_encounter
(date_created, kid_1_id, kid_2_id)
values (sysdate, p_kid_id, i.id);
commit;
WHEN OTHERS THEN
dbms_output.put_line(SUBSTR(SQLERRM, 1, 200));
end;
end if;
end loop;
EXCEPTION WHEN OTHERS THEN
NULL;
end checkNeighbours;
end children_functions;
/
set serveroutput on;
declare
v_user_id authentication_account.id%type := 1; --189
distribution children_functions.age_distribution;
begin
dbms_output.put_line('The user '||v_user_id||' has: '||children_functions.getAge(v_user_id)||' years');
for i in 0..10 loop
dbms_output.put_line(i||' '||children_functions.getAgeDistribution(i)||'%');
end loop;
dbms_output.put_line(children_functions.getDistance(9, 7, 3, 2));
end;
/
set serveroutput on;
declare
v_distance float;
v_x1 float := 0.340978812473806;
v_x2 float := -0.633783394530149;
v_y1 float := -0.940070981066831;
v_y2 float := -1.16331667485907;
begin
dbms_output.put_line(v_x1 + v_x2);
v_distance := children_functions.getDistance(v_x1, v_y1, v_x2, v_y2);
dbms_output.put_line(v_distance);
end;
/
| true |
9c55ffdef88dbcc8447cb377ee761847a7200e2a | SQL | StewartLivingstone/node1 | /vet_tables.sql | UTF-8 | 3,770 | 3.765625 | 4 | [] | no_license | USE vet_tables;
DROP TABLE owner;
DROP TABLE pet;
DROP TABLE practice;
DROP TABLE vet;
#-- Create the owner table
CREATE TABLE owner
( owner_id INTEGER NOT NULL
, surname CHAR VARYING(25) NOT NULL
, forename CHAR VARYING(20) NOT NULL
, title CHAR VARYING(4) NOT NULL
, tel_number CHAR VARYING(15)
, address CHAR VARYING(50) NOT NULL
, PRIMARY KEY (owner_id)
);
#-- Insert data into the owner table
INSERT INTO owner VALUES (1, 'Jackson', 'Janet', 'Miss', '0141-223321', '1, Main Street, Glasgow');
INSERT INTO owner VALUES (2, 'Singh', 'Raj', 'Mr', '0141-326535', '22, The Hill, Glasgow');
INSERT INTO owner VALUES (3, 'Campbell', 'Bernard', 'Mr', '0143-46532', '21, High Street, Glasgow');
INSERT INTO owner VALUES (4, 'Hussain', 'Pauline', 'Mrs', '0142-68543', '51, Elm Grove, Glasgow');
INSERT INTO owner VALUES (5, 'Otten', 'Gerard', 'Dr', '0141-557536', '77, The Walk, Glasgow');
#-- Create the pet table
#-- Born is year of birth, e.g. 1999
CREATE TABLE pet
( pet_id CHAR(5) NOT NULL
, name CHAR VARYING(25) NOT NULL
, type CHAR VARYING(15) NOT NULL
, breed CHAR VARYING(15) NOT NULL
, gender CHAR(1)
, born INTEGER
, owner_id INTEGER NOT NULL
, notes CHAR VARYING(100)
, PRIMARY KEY (pet_id)
);
#-- Insert data into the pet table
INSERT INTO pet VALUES ('P0001', 'Tiddles', 'cat', 'persian', 'F', 1998, 2, 'Has a bad temper and scratches you');
INSERT INTO pet VALUES ('P0002', 'Lassie', 'dog', 'retriever', 'M', 2001, 5, 'Allergic to penicillin');
INSERT INTO pet VALUES ('P0005', 'Jaws', 'fish', 'goldfish', 'X', NULL, 2, NULL);
INSERT INTO pet VALUES ('P0024', 'Spot', 'dog', 'mongrel', 'M', 1996, 4, 'Very docile');
INSERT INTO pet VALUES ('P0078', 'Trigger', 'horse', 'shire', 'F', 1988, 1, 'Allergic to penicillin');
INSERT INTO pet VALUES ('P0089', 'Lassie', 'dog', 'sheepdog', 'M', 2001, 3, 'Poor heart');
INSERT INTO pet VALUES ('P0097', 'Jaws 2', 'fish', 'angel', 'X', NULL, 2, NULL);
INSERT INTO pet VALUES ('P0132', 'Ginger', 'cat', 'siamese', 'F', 2000, 4, 'Bad tempered');
INSERT INTO pet VALUES ('P0145', 'Shep', 'dog', 'sheepdog', 'M', 1993, 5, 'Eats everything');
INSERT INTO pet VALUES ('P0342', 'Slippy', 'snake', 'addder', 'X', 2002, 1, NULL);
#-- Create the practice table
CREATE TABLE practice
( practice_id CHAR(2) NOT NULL
, practice_name CHAR VARYING(20) NOT NULL
, practice_address CHAR VARYING(50) NOT NULL
, PRIMARY KEY (practice_id)
);
#-- Insert data into the practice table
INSERT INTO practice VALUES ('P1', 'Practice Head Office', '27, The Hill, Glasgow');
INSERT INTO practice VALUES ('P2', 'Practice Unit 1', 'Unit 1, Houston Estate, Glasgow');
#-- Create the vet table
CREATE TABLE vet
( vet_id CHAR(3) NOT NULL
, surname CHAR VARYING(25) NOT NULL
, forename CHAR VARYING(20) NOT NULL
, title CHAR VARYING(4) NOT NULL
, ext_number INTEGER NOT NULL
, position CHAR VARYING(14) NOT NULL
, salary DECIMAL(7,2) NOT NULL
, practice_id CHAR(2)
, PRIMARY KEY (vet_id)
);
#-- Insert data into the vet table
INSERT INTO vet VALUES ('V01', 'Wilson', 'Sarah', 'Dr', 6122, 'Senior Partner', 45000, 'P1');
INSERT INTO vet VALUES ('V02', 'McDonald', 'Bryan', 'Dr', 6154, 'Senior Partner', 35000, 'P1');
INSERT INTO vet VALUES ('V03', 'Patel', 'Jane', 'Dr', 6165, 'Junior Partner', 29000, 'P2');
INSERT INTO vet VALUES ('V04', 'McCafferty', 'Trevor', 'Mr', 6166, 'Junior Partner', 25600, 'P2');
#-- Commit the data to the database, i.e. make it permanent
COMMIT;
#-- List the tables created
#SELECT * FROM cat;
SHOW TABLES;
#-- Count the number of rows in each table
#SET HEADING OFF
SELECT 'Owner ', COUNT(*) FROM owner;
SELECT 'Pet ', COUNT(*) FROM pet;
SELECT 'Practice', COUNT(*) FROM practice;
SELECT 'Vet ', COUNT(*) FROM vet;
#SET HEADING ON
| true |
e13a983df43ad2f752a8c24528dfdef314c9aa4e | SQL | debramaelee/sql-exercises | /restaurant_db.sql | UTF-8 | 2,841 | 4 | 4 | [] | no_license | CREATE TABLE restaurant (
id serial PRIMARY KEY,
name varchar,
distance numeric,
stars integer CHECK (stars <= 5),
category varchar,
favorite_dish varchar,
does_takeout boolean,
last_time_eaten_there date
);
-- Write INSERT statements to enter data into the restaurant table. You can paste the statements into the psql shell.
insert into restaurant values
(default,'Chipotle', 0.1, 4, 'Mexican', 'Burrito', 't', '2017-03-27'),
(default, 'Farm Burger', 0.1, 5, 'Burgers', 'Tres Leches Shake', 't', '2017-03-19'),
(default, 'Wagaya', 8.7, 5, 'Japanese', 'Ramen', 'n', '2017-3-24'),
(default, 'BarTaco', 5, 2, 'Mexican', 'Churro', 'n', '2017-03-22'),
(default, 'Iron Age', 16.7, 5, 'Korean', 'Pork Belly', 'n', '2017-03-21'),
(default, 'Fox Bros', 6.5, 5, 'BBQ', 'Frito Pie', 'y', '2017-01-30'),
(default, 'NaanStop', 0.2, 4, 'Indian', 'Curry', 'y', '2017-02-05')
-- Write queries to get:
-- The names of the restaurants that you gave a 5 stars to
\! echo "5 star restaurant names:"
select name from restaurant where stars = 5;
-- The favorite dishes of all 5-star restaurants
select favorite_dish from restaurant;
-- The the id of a restaurant by a specific restaurant name, say 'NaanStop'
select id from restaurant where name = 'NaanStop';
-- restaurants in the category of 'BBQ'
select name from restaurant where category = 'BBQ';
-- restaurants that do take out
select name from restaurant where does_takeout = 'y';
-- restaurants that do take out and is in the category of 'BBQ'
select name from restaurant where does_takeout = 'y' and category = 'BBQ';
-- restaurants within 2 miles
select name from restaurant where distance <= 2;
-- restaurants you haven't ate at in the last week
select name from restaurant where last_time_eaten_there BETWEEN '1991-03-20' AND '2017-03-20';
-- restaurants you haven't ate at in the last week and has 5 stars
select name from restaurant where last_time_eaten_there BETWEEN '1991-03-20' AND '2017-03-20' AND stars = '5';
-- list restaurants by the closest distance.
select * from restaurant order by distance;
-- list the top 2 restaurants by distance.
select * from restaurant order by distance limit 2;
-- list the top 2 restaurants by stars.
select * from restaurant order by stars desc limit 2;
-- list the top 2 restaurants by stars where the distance is less than 2 miles.
select * from restaurant where distance <=2 order by stars desc;
-- count the number of restaurants in the db.
select count(*) from restaurant;
-- count the number of restaurants by category.
select category, count(*) from restaurant group by category;
-- get the average stars per restaurant by category.
select category, avg(stars) from restaurant group by category;
-- get the max stars of a restaurant by category.
select category, max(stars) from restaurant group by category;
| true |
1adca67fda9eb5f0fd0587c6da9bdd48ad1cd257 | SQL | Erv16/Student-Registration-System | /package_tables.sql | UTF-8 | 11,944 | 3.828125 | 4 | [] | no_license | SET serveroutput ON;
CREATE OR REPLACE PACKAGE student_registration AS
TYPE ref_cursor is ref cursor;
FUNCTION show_students RETURN ref_cursor;
FUNCTION show_courses RETURN ref_cursor;
FUNCTION show_pre_requisites RETURN ref_cursor;
FUNCTION show_classes RETURN ref_cursor;
FUNCTION show_enrollments RETURN ref_cursor;
FUNCTION show_logs RETURN ref_cursor;
PROCEDURE add_student(sid_in IN students.sid%TYPE, firstname_in IN students.firstname%TYPE, lastname_in IN students.lastname%TYPE, status_in IN students.status%TYPE, gpa_in IN students.gpa%TYPE, email_in IN students.email%TYPE, msg OUT VARCHAR2);
PROCEDURE get_student_class_information(sid_in IN students.sid%TYPE, error_msg OUT varchar2, rc_cursor OUT SYS_REFCURSOR);
PROCEDURE get_class_information(classid_in IN classes.classid%TYPE, error_msg OUT varchar2, rc_cursor OUT SYS_REFCURSOR);
PROCEDURE get_prerequisites(dept_code_in IN prerequisites.dept_code%TYPE, course_no_in IN prerequisites.course_no%TYPE, rc_cursor OUT SYS_REFCURSOR);
PROCEDURE prerequisites_grade_check(dept_code_in IN prerequisites.dept_code%TYPE, course_no_in IN prerequisites.course_no%TYPE, rc_cursor OUT SYS_REFCURSOR);
PROCEDURE enroll_student(sid_in IN students.sid%TYPE, classid_in IN classes.classid%TYPE, msg OUT varchar2);
PROCEDURE drop_student_enrollment(sid_in IN students.sid%TYPE, classid_in IN classes.classid%TYPE, msg OUT VARCHAR2);
PROCEDURE delete_student(sid_in IN students.sid%TYPE, msg OUT VARCHAR2);
END;
/
CREATE OR REPLACE PACKAGE BODY student_registration AS
FUNCTION show_students RETURN ref_cursor AS rc ref_cursor;
BEGIN
OPEN rc FOR
SELECT * FROM students;
RETURN rc;
END;
FUNCTION show_courses RETURN ref_cursor AS rc ref_cursor;
BEGIN
OPEN rc FOR
SELECT * FROM courses;
RETURN rc;
END;
FUNCTION show_pre_requisites RETURN ref_cursor AS rc ref_cursor;
BEGIN
OPEN rc FOR
SELECT * FROM prerequisites;
RETURN rc;
END;
FUNCTION show_classes RETURN ref_cursor AS rc ref_cursor;
BEGIN
OPEN rc FOR
SELECT * FROM classes;
RETURN rc;
END;
FUNCTION show_enrollments RETURN ref_cursor AS rc ref_cursor;
BEGIN
OPEN rc FOR
SELECT * FROM enrollments
ORDER BY sid;
RETURN rc;
END;
FUNCTION show_logs RETURN ref_cursor AS rc ref_cursor;
BEGIN
OPEN rc FOR
SELECT * FROM logs;
RETURN rc;
END;
PROCEDURE get_student_class_information(sid_in IN students.sid%TYPE, error_msg OUT varchar2, rc_cursor OUT SYS_REFCURSOR) IS
student_exists number;
student_enrolled number;
BEGIN
SELECT COUNT(sid) INTO student_exists FROM students WHERE sid = sid_in;
SELECT COUNT(sid) INTO student_enrolled FROM enrollments WHERE sid = sid_in;
IF student_exists = 0 THEN
error_msg := 'The sid is invalid';
ELSIF student_enrolled = 0 THEN
error_msg := 'The student has not taken any course';
ELSE
OPEN rc_cursor FOR
SELECT s.sid, s.lastname, s.status, cl.classid, CONCAT(cl.dept_code, cl.course_no) AS course, c.title, cl.year, cl.semester
FROM students s
INNER JOIN enrollments e
ON s.sid = e.sid
INNER JOIN classes cl
ON e.classid = cl.classid
INNER JOIN courses c
ON cl.dept_code = c.dept_code AND cl.course_no = c.course_no
WHERE s.sid = sid_in;
END IF;
END;
PROCEDURE get_class_information(classid_in IN classes.classid%TYPE, error_msg OUT varchar2, rc_cursor OUT SYS_REFCURSOR) IS
class_exists number;
students_enrolled number;
BEGIN
SELECT COUNT(classid) INTO class_exists FROM classes WHERE classid = classid_in;
SELECT COUNT(e.sid) INTO students_enrolled FROM classes cl, enrollments e WHERE cl.classid = classid_in AND cl.classid = e.classid;
IF class_exists = 0 THEN
error_msg := 'The class is invalid';
ELSIF students_enrolled = 0 THEN
error_msg := 'No student is enrolled in the class';
ELSE
OPEN rc_cursor FOR
SELECT cl.classid, c.title, cl.semester, cl.year, s.sid, s.lastname
FROM classes cl
INNER JOIN courses c
ON cl.dept_code = c.dept_code AND cl.course_no = c.course_no
INNER JOIN enrollments e
ON e.classid = cl.classid
INNER JOIN students s
ON e.sid = s.sid
WHERE cl.classid = classid_in;
END IF;
END;
PROCEDURE add_student(sid_in IN students.sid%TYPE, firstname_in IN students.firstname%TYPE, lastname_in IN students.lastname%TYPE, status_in IN students.status%TYPE, gpa_in IN students.gpa%TYPE, email_in IN students.email%TYPE, msg OUT VARCHAR2) AS
BEGIN
INSERT INTO students(sid, firstname, lastname, status, gpa, email) VALUES(sid_in, firstname_in, lastname_in, status_in, gpa_in, email_in);
msg := 'Student added successfully';
END;
PROCEDURE get_prerequisites(dept_code_in IN prerequisites.dept_code%TYPE, course_no_in IN prerequisites.course_no%TYPE, rc_cursor OUT SYS_REFCURSOR) IS
CURSOR prereq_cursor IS
SELECT pre_dept_code, pre_course_no FROM prerequisites
WHERE dept_code = dept_code_in AND course_no = course_no_in;
temp_cursor prereq_cursor%ROWTYPE;
BEGIN
INSERT INTO prereq_courses_temp_table SELECT pre_dept_code, pre_course_no FROM prerequisites WHERE dept_code=dept_code_in AND course_no=course_no_in;
OPEN prereq_cursor;
LOOP
FETCH prereq_cursor INTO temp_cursor;
EXIT WHEN prereq_cursor%NOTFOUND;
get_prerequisites(temp_cursor.pre_dept_code,temp_cursor.pre_course_no,rc_cursor);
END LOOP;
OPEN rc_cursor FOR SELECT CONCAT(dept_code,course_no) AS "prerequisite courses" FROM prereq_courses_temp_table;
CLOSE prereq_cursor;
END;
PROCEDURE prerequisites_grade_check(dept_code_in IN prerequisites.dept_code%TYPE, course_no_in IN prerequisites.course_no%TYPE, rc_cursor OUT SYS_REFCURSOR) IS
CURSOR prereq_grade_cursor IS
SELECT pre_dept_code, pre_course_no FROM prerequisites
WHERE dept_code = dept_code_in AND course_no = course_no_in;
temp_cursor prereq_grade_cursor%ROWTYPE;
BEGIN
INSERT INTO prereq_courses_temp_table SELECT pre_dept_code, pre_course_no FROM prerequisites WHERE dept_code = dept_code_in AND course_no = course_no_in;
OPEN prereq_grade_cursor;
LOOP
FETCH prereq_grade_cursor INTO temp_cursor;
EXIT WHEN prereq_grade_cursor%NOTFOUND;
prerequisites_grade_check(temp_cursor.pre_dept_code,temp_cursor.pre_course_no,rc_cursor);
END LOOP;
OPEN rc_cursor FOR SELECT dept_code, course_no FROM prereq_courses_temp_table;
CLOSE prereq_grade_cursor;
END;
PROCEDURE enroll_student(sid_in IN students.sid%TYPE, classid_in IN classes.classid%TYPE, msg OUT VARCHAR2) AS
student_exists number;
class_exists number;
student_enrolled NUMBER;
cl_size classes.class_size%TYPE;
cl_limit classes.class_size%TYPE;
cl_year classes.year%TYPE;
cl_semester classes.semester%TYPE;
cl_dept_code classes.dept_code%TYPE;
cl_course_no classes.course_no%TYPE;
courses_enrolled NUMBER;
pre_reqs_enrolled NUMBER;
pre_reqs_exists NUMBER;
temp_cursor SYS_REFCURSOR;
cursor_dept_code prerequisites.dept_code%TYPE;
cursor_course_no prerequisites.course_no%TYPE;
BEGIN
SELECT COUNT(*) INTO student_exists FROM students WHERE students.sid = sid_in;
SELECT COUNT(*) INTO class_exists FROM classes WHERE classes.classid = classid_in;
IF(student_exists = 0) THEN
msg := 'The sid is invalid';
ELSE
IF(class_exists = 0) THEN
msg := 'The class is invalid';
ELSE
SELECT class_size, limit INTO cl_size, cl_limit FROM classes WHERE classid = classid_in;
IF(cl_size + 1 > cl_limit) THEN
msg := 'The class is full';
ELSE
SELECT COUNT(*) INTO student_enrolled FROM enrollments WHERE sid = sid_in AND classid = classid_in;
IF(student_enrolled > 0) THEN
msg := 'The student is already in this class';
ELSE
SELECT dept_code, course_no INTO cl_dept_code, cl_course_no FROM classes WHERE classid = classid_in;
prerequisites_grade_check(cl_dept_code, cl_course_no, temp_cursor);
SELECT COUNT(*) INTO pre_reqs_exists FROM prereq_courses_temp_table;
SELECT year, semester INTO cl_year, cl_semester FROM classes WHERE classid = classid_in;
SELECT COUNT(*) INTO courses_enrolled FROM enrollments WHERE sid = sid_in AND classid IN(
SELECT classid FROM classes WHERE year = cl_year AND semester = cl_semester AND classid <> classid_in
);
IF(pre_reqs_exists > 0) THEN
LOOP
FETCH temp_cursor INTO cursor_dept_code, cursor_course_no;
EXIT WHEN temp_cursor%NOTFOUND;
SELECT COUNT(*) INTO pre_reqs_enrolled FROM enrollments e WHERE e.classid IN (SELECT classid FROM classes WHERE dept_code = cursor_dept_code AND course_no = cursor_course_no)
AND e.lgrade IS NOT NULL AND e.lgrade NOT IN ('C-','D','F','I') AND e.sid = sid_in;
END LOOP;
IF(pre_reqs_enrolled > 0) THEN
IF(courses_enrolled >= 4) THEN
msg := 'Students cannot be enrolled in more than four classes in the same semester';
ELSE
IF(courses_enrolled = 3) THEN
msg := 'You are overloaded';
INSERT INTO enrollments VALUES(sid_in, classid_in, null);
ELSE
INSERT INTO enrollments VALUES(sid_in, classid_in, null);
msg := 'Student '||sid_in||' has been enrolled for class '||classid_in||' successfully';
END IF;
END IF;
ELSE
msg := 'Prerequisite not satisfied';
END IF;
ELSE
IF(courses_enrolled >= 4) THEN
msg := 'Students cannot be enrolled in more than four classes in the same semester';
ELSE
IF(courses_enrolled = 3) THEN
msg := 'You are overloaded';
INSERT INTO enrollments VALUES(sid_in, classid_in, null);
ELSE
INSERT INTO enrollments VALUES(sid_in, classid_in, null);
msg := 'Student '||sid_in||' has been enrolled for class '||classid_in||' successfully';
END IF;
END IF;
END IF;
END IF;
END IF;
END IF;
END IF;
END;
PROCEDURE drop_student_enrollment(sid_in IN students.sid%TYPE, classid_in IN classes.classid%TYPE, msg OUT VARCHAR2) IS
sid_exists NUMBER;
classid_exists NUMBER;
enrollment_exists NUMBER;
prereq_check NUMBER;
class_strength NUMBER;
last_class_check NUMBER;
BEGIN
SELECT COUNT(*) INTO sid_exists FROM students s WHERE s.sid = sid_in;
SELECT COUNT(*) INTO classid_exists FROM classes cl WHERE cl.classid = classid_in;
IF(sid_exists = 0) THEN
msg := 'The sid is invalid';
ELSE
IF(classid_exists = 0) THEN
msg := 'classid not found';
ELSE
SELECT COUNT(*) INTO enrollment_exists FROM enrollments e WHERE e.sid = sid_in AND e.classid = classid_in;
IF(enrollment_exists = 0) THEN
msg := 'The student is not enrolled in the class';
ELSE
SELECT COUNT(*) INTO prereq_check FROM classes cl, prerequisites p WHERE cl.classid = classid_in AND cl.dept_code = p.pre_dept_code AND cl.course_no = p.pre_course_no AND (p.dept_code, p.course_no) IN
(SELECT cl.dept_code, cl.course_no FROM enrollments e, classes cl WHERE e.classid = cl.classid AND e.sid = sid_in);
IF(prereq_check > 0) THEN
msg := 'The drop is not permitted because another class uses it as a prerequisite.';
ELSE
DELETE FROM enrollments e WHERE e.sid = sid_in AND e.classid = classid_in;
msg := 'The student '||sid_in||' has been dropped from class '||classid_in||' successfully';
SELECT cl.class_size INTO class_strength FROM classes cl WHERE cl.classid = classid_in;
SELECT COUNT(*) INTO last_class_check FROM enrollments e WHERE e.sid = sid_in;
IF(class_strength = 0) THEN
msg := 'The class now has no students';
ELSE
IF(last_class_check = 0) THEN
msg := 'This student is enrolled in no class';
END IF;
END IF;
END IF;
END IF;
END IF;
END IF;
END;
PROCEDURE delete_student(sid_in IN students.sid%TYPE, msg OUT VARCHAR2) IS
student_exists NUMBER;
BEGIN
SELECT COUNT(*) INTO student_exists FROM students s WHERE s.sid = sid_in;
IF(student_exists = 0) THEN
msg := 'sid not found';
ELSE
DELETE FROM students s WHERE s.sid = sid_in;
COMMIT;
msg := 'Student '||sid_in||' has been removed successfully';
END IF;
END;
END;
/
show error;
| true |
d351595c5c3772b4477d4ea01a9956fc1b65ac7e | SQL | dbmdz/cudami | /dc-cudami-server/dc-cudami-server-backend-jdbi/src/main/resources/de/digitalcollections/cudami/server/backend/impl/database/migration/V10.00.00__DDL_Table_for_Licenses.sql | UTF-8 | 245 | 2.703125 | 3 | [
"MIT"
] | permissive | CREATE TABLE IF NOT EXISTS licenses (
uuid UUID NOT NULL PRIMARY KEY,
acronym VARCHAR COLLATE "ucs_basic",
label JSONB,
url VARCHAR COLLATE "ucs_basic" NOT NULL UNIQUE,
created TIMESTAMP NOT NULL,
last_modified TIMESTAMP NOT NULL
); | true |
bb2dec1d9fde3d8098049df7b373e30f12ceea44 | SQL | EricRicketts/LaunchSchool | /SQL/DatabaseApplications/interacting_with_a_database_in_code/command_line_project/schema.sql | UTF-8 | 201 | 2.875 | 3 | [] | no_license | CREATE TABLE expenses (
id SERIAL PRIMARY KEY,
amount DECIMAL(6, 2) NOT NULL CHECK (amount >= 0.01),
memo TEXT NOT NULL,
created_on TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP(0)
); | true |
3b1fc1aea19056b70e439219e334d943f38f30d8 | SQL | leolanavo/MAC0350 | /EP1/scripts/DDL.sql | UTF-8 | 4,475 | 3.546875 | 4 | [] | no_license | CREATE TABLE IF NOT EXISTS USUARIO(
US_ID SERIAL PRIMARY KEY NOT NULL,
US_LOGIN CHAR(320) NOT NULL,
US_SENHA CHAR(12) NOT NULL
);
CREATE TABLE IF NOT EXISTS ALUNO(
AL_ID SERIAL PRIMARY KEY NOT NULL,
AL_NUSP INT NOT NULL UNIQUE CHECK(AL_NUSP >= 1000 AND AL_NUSP < 1000000000),
AL_NOME CHAR(50) NOT NULL,
AL_DATA_MATRICULA INT NOT NULL CHECK(AL_DATA_MATRICULA >= 1970),
AL_DATA_FORMATURA INT CHECK(AL_DATA_MATRICULA >= 1974),
AL_USER_ID INT references USUARIO(US_ID)
);
CREATE TABLE IF NOT EXISTS PROFESSOR(
PR_ID SERIAL PRIMARY KEY NOT NULL,
PR_NUSP INT NOT NULL UNIQUE,
PR_NOME CHAR(50) NOT NULL,
PR_AREA CHAR(50) NOT NULL,
PR_USER_ID INT references USUARIO(US_ID)
);
CREATE TABLE IF NOT EXISTS PERFIL(
PE_ID SERIAL PRIMARY KEY NOT NULL,
PE_NOME CHAR(50) NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS SERVICO(
SR_ID SERIAL PRIMARY KEY NOT NULL,
SR_NOME CHAR(50) NOT NULL UNIQUE,
SR_DESCRICAO TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS DISCIPLINA(
DS_ID SERIAL PRIMARY KEY NOT NULL,
DS_CODIGO CHAR(7) NOT NULL UNIQUE,
DS_NOME CHAR(50) NOT NULL,
DS_CREDITO_AULA INT NOT NULL CHECK(DS_CREDITO_AULA >= 0 AND DS_CREDITO_AULA <= 40),
DS_CREDITO_TRAB INT NOT NULL CHECK(DS_CREDITO_TRAB >= 0 AND DS_CREDITO_TRAB <= 40),
DS_SEMESTRE INT NOT NULL CHECK(DS_SEMESTRE >= 1 AND DS_SEMESTRE <= 2),
DS_LOCAL CHAR(10) NOT NULL,
DS_EMENTA TEXT NOT NULL,
DS_APROVEITAMENTO INT NOT NULL, CHECK(DS_APROVEITAMENTO >= 0 AND DS_APROVEITAMENTO <= 2)
);
CREATE TABLE IF NOT EXISTS MODULO(
MD_ID SERIAL PRIMARY KEY NOT NULL,
MD_NOME CHAR(50) NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS TRILHA(
TR_ID SERIAL PRIMARY KEY NOT NULL,
TR_NOME CHAR(50) NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS PERFIL_USA_SERVICO(
PERFIL_ID INT references PERFIL(PE_ID),
SERVICO_ID INT references SERVICO(SR_ID),
CONSTRAINT PE_SE PRIMARY KEY (PERFIL_ID, SERVICO_ID)
);
CREATE TABLE IF NOT EXISTS E_PRE_REQUESITO(
DISCIPLINA_ID INT references DISCIPLINA(DS_ID),
REQUESITO_ID INT references DISCIPLINA(DS_ID)
);
CREATE TABLE IF NOT EXISTS OPTATIVA_FORMA_MODULO(
OPTATIVA_ID INT references DISCIPLINA(DS_ID),
MODULO_ID INT references MODULO(MD_ID),
CONSTRAINT OP_MD PRIMARY KEY (OPTATIVA_ID, MODULO_ID)
);
CREATE TABLE IF NOT EXISTS ALUNO_CURSA_DISCIPLINA(
ALUNO_ID INT references ALUNO(AL_ID),
DISCIPLINA_ID INT references DISCIPLINA(DS_ID),
PRETENDE_SEM INT NOT NULL CHECK(PRETENDE_SEM >= 1 AND PRETENDE_SEM <= 2),
PRETENDE_ANO INT NOT NULL CHECK(PRETENDE_ANO >= 1970),
STATUS INT NOT NULL CHECK(STATUS >= 0 AND STATUS <= 2),
CONSTRAINT AL_DI PRIMARY KEY (ALUNO_ID, DISCIPLINA_ID)
);
CREATE TABLE IF NOT EXISTS USUARIO_TEM_PERFIL(
USUARIO_ID INT references USUARIO(US_ID),
PERFIL_ID INT references PERFIL(PE_ID),
CONSTRAINT US_PE PRIMARY KEY (USUARIO_ID, PERFIL_ID)
);
CREATE TABLE IF NOT EXISTS MODULO_PERTENCE_TRILHA(
MODULO_ID INT references MODULO(MD_ID),
TRILHA_ID INT references TRILHA(TR_ID),
MINIMO INT NOT NULL CHECK(MINIMO >= 1),
CONSTRAINT MD_TR PRIMARY KEY (MODULO_ID, TRILHA_ID)
);
CREATE TABLE IF NOT EXISTS PROFESSOR_TUTORA_ALUNO(
PROFESSOR_ID INT references PROFESSOR(PR_ID),
ALUNO_ID INT references ALUNO(AL_ID),
CONSTRAINT PR_AL PRIMARY KEY (PROFESSOR_ID, ALUNO_ID)
);
| true |
363bfcc58fa81fc632e75d0fa4afda745e34e436 | SQL | gcoronelc/PLSQL-2019-08 | /Clase02/enrique melendez.sql | ISO-8859-1 | 1,008 | 3.171875 | 3 | [] | no_license | /* Ejercicio
Desarrollar una funcion que retorne la cantidad de dias de un mes
*/
CREATE OR REPLACE FUNCTION FN_DIAS_MES
(P_MES IN NUMBER) RETURN VARCHAR2
IS
V_DIAS VARCHAR2(100);
BEGIN
CASE P_MES
WHEN 1 THEN V_DIAS := 'ENERO'||' - '||'31 DAS' ;
WHEN 2 THEN V_DIAS := 'FEBRERO'||' - '||'28 DAS';
WHEN 3 THEN V_DIAS := 'MARZO'||' - '||'31 DAS';
WHEN 4 THEN V_DIAS := 'ABRIL'||' - '||'30 DAS';
WHEN 5 THEN V_DIAS := 'MAYO'||' - '||'31 DAS';
WHEN 6 THEN V_DIAS := 'JUNIO'||' - '||'30 DAS';
WHEN 7 THEN V_DIAS := 'JULIO'||' - '||'31 DAS';
WHEN 8 THEN V_DIAS := 'AGOSTO'||' - '||'31 DAS';
WHEN 9 THEN V_DIAS := 'SETIEMBRE'||' - '||'30 DAS';
WHEN 10 THEN V_DIAS := 'OCTUBRE'||' - '||'31 DAS';
WHEN 11 THEN V_DIAS := 'NOVIEMBRE'||' - '||'30 DAS';
WHEN 12 THEN V_DIAS := 'DICIEMBRE'||' - '||'31 DAS';
ELSE V_DIAS := 'NO ES UN MES VALIDO';
END CASE;
RETURN V_DIAS;
END;
/
SELECT FN_DIAS_MES(12) FROM DUAL; | true |
b78f4f8f74973b92a475a76e1c4ba7ccc285523f | SQL | hectorh30/cc3057-2017 | /proyectos/proyecto2-dbms/false-tests.sql | UTF-8 | 212 | 2.875 | 3 | [] | no_license | SELECT FROM estudiantes;
INSERT INTO estudiante VALUES ('A', 'B'), ('C', 'D');
SELECT nombre FROM estudiante JOIN profesor ON estudiante.profesor_id = profesor.id WHERE estudiante.nombre = 'Pedro' ORDER BY DESC;
| true |
f380d64f231303ff6449ea9f5347b1668f67cd8f | SQL | getbehindthmule/oath2-security | /src/main/resources/db/migration/V1.0__create_oauth2_schema.sql | UTF-8 | 2,466 | 3.46875 | 3 | [] | no_license | -- noinspection SpellCheckingInspectionForFile
CREATE SEQUENCE HIBERNATE_SEQUENCE START WITH 100 INCREMENT BY 1;
CREATE TABLE OAUTH_CLIENT_DETAILS
(
CLIENT_ID VARCHAR(255) PRIMARY KEY,
RESOURCE_IDS VARCHAR(255),
CLIENT_SECRET VARCHAR(255),
SCOPE VARCHAR(255),
AUTHORIZED_GRANT_TYPES VARCHAR(255),
WEB_SERVER_REDIRECT_URI VARCHAR(255),
AUTHORITIES VARCHAR(255),
ACCESS_TOKEN_VALIDITY INTEGER,
REFRESH_TOKEN_VALIDITY INTEGER,
ADDITIONAL_INFORMATION VARCHAR(4096),
AUTOAPPROVE VARCHAR(255)
);
CREATE TABLE OAUTH_CLIENT_TOKEN
(
TOKEN_ID VARCHAR(255),
TOKEN VARBINARY,
AUTHENTICATION_ID VARCHAR(255) PRIMARY KEY,
USER_NAME VARCHAR(255),
CLIENT_ID VARCHAR(255)
);
CREATE TABLE OAUTH_ACCESS_TOKEN
(
TOKEN_ID VARCHAR(255),
TOKEN VARBINARY,
AUTHENTICATION_ID VARCHAR(255) PRIMARY KEY,
USER_NAME VARCHAR(255),
CLIENT_ID VARCHAR(255),
AUTHENTICATION VARBINARY,
REFRESH_TOKEN VARCHAR(255)
);
CREATE TABLE OAUTH_REFRESH_TOKEN
(
TOKEN_ID VARCHAR(255),
TOKEN VARBINARY,
AUTHENTICATION VARBINARY
);
CREATE TABLE OAUTH_CODE
(
CODE VARCHAR(255),
AUTHENTICATION VARBINARY
);
CREATE TABLE OAUTH_APPROVALS
(
USERID VARCHAR(255),
CLIENTID VARCHAR(255),
SCOPE VARCHAR(255),
STATUS VARCHAR(10),
EXPIRESAT TIMESTAMP,
LASTMODIFIEDAT TIMESTAMP
);
CREATE TABLE AUTHORITY
(
ID BIGINT GENERATED BY DEFAULT AS IDENTITY,
NAME VARCHAR(255),
PRIMARY KEY (ID)
);
ALTER TABLE AUTHORITY
ADD CONSTRAINT AUTHORITY_NAME UNIQUE (NAME);
CREATE TABLE USER_
(
ID BIGINT GENERATED BY DEFAULT AS IDENTITY,
PASSWORD VARCHAR(255),
USER_NAME VARCHAR(255),
ACCOUNT_EXPIRED BOOLEAN,
ACCOUNT_LOCKED BOOLEAN,
CREDENTIALS_EXPIRED BOOLEAN,
ENABLED BOOLEAN,
PRIMARY KEY (ID)
);
ALTER TABLE USER_
ADD CONSTRAINT USER_USER_NAME UNIQUE (USER_NAME);
CREATE TABLE USERS_AUTHORITIES
(
USER_ID BIGINT NOT NULL,
AUTHORITY_ID BIGINT NOT NULL,
PRIMARY KEY (USER_ID, AUTHORITY_ID)
);
ALTER TABLE USERS_AUTHORITIES
ADD CONSTRAINT USERS_AUTHORITIES_AUTHORITY
FOREIGN KEY (AUTHORITY_ID) REFERENCES AUTHORITY;
ALTER TABLE USERS_AUTHORITIES
ADD CONSTRAINT USERS_AUTHORITIES_USER_
FOREIGN KEY (USER_ID) REFERENCES USER_;
| true |
c90d89d47d4c8472f8bb9f4ae7bc5349bc4b9e0c | SQL | colorfishwyl/alibabaService | /database/更新主键自增序列.sql | UTF-8 | 343 | 2.671875 | 3 | [] | no_license | - SELECT MAX(id) FROM illuminations; -- 获得该表当前最大id值
-- SELECT nextval('"illuminations_id_seq"'); -- 获得该表id自增序列值
SELECT setval('"illuminations_id_seq"', (SELECT MAX(id) FROM illuminations)); -- 更新设置当前id自增序列值为最大id
--SELECT nextval('"illuminations_id_seq"'); -- 查看下一个id
| true |
e9efcd708f7d5372898cabbe7b121e4a040e71c6 | SQL | luo-hang/study-www-association-qa | /study-www-association-qa/sql/shiant-study.sql | UTF-8 | 9,563 | 2.828125 | 3 | [] | no_license | -- ----------------------------
-- Table structure for t_sys_carousel
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_carousel`;
CREATE TABLE `t_sys_carousel` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
`title` varchar(500) DEFAULT NULL COMMENT '标题',
`domain` varchar(255) NOT NULL COMMENT '域名',
`url` varchar(255) DEFAULT NULL COMMENT '超链接',
`file_url` varchar(500) DEFAULT NULL COMMENT '文件地址',
`order` int(11) NOT NULL COMMENT '排序',
`create_date` datetime DEFAULT NULL COMMENT '创建时间',
`update_date` datetime DEFAULT NULL COMMENT '更新时间',
`creater` varchar(20) DEFAULT NULL COMMENT '创建人',
`updater` varchar(20) DEFAULT NULL COMMENT '更新人',
`is_delete` bigint(2) DEFAULT '0' COMMENT '删除标记',
PRIMARY KEY (`id`),
KEY `index_1` (`domain`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_sys_carousel
-- ----------------------------
INSERT INTO `t_sys_carousel` VALUES ('1', ' <p>\n 已为<b style=\"color:#FFB800;font-size: 14px;\">5625</b>名学员提供培训服务 \n 累计观看次数达<b style=\"color:#FFB800;font-size: 14px;\">87090</b>次\n </p> ', 'jiaoyu.shanhaiyh.com', '', 'http://shiant-oss-common.oss-cn-shenzhen.aliyuncs.com/portal/carousel/a8937c06-e521-4d15-8e0f-91828fb3e926.jpg', '1', '2020-06-03 16:32:20', '2020-06-22 17:49:01', '管理员', '管理员', '0');
INSERT INTO `t_sys_carousel` VALUES ('2', ' <p>\n 已为<b style=\"color:#FFB800;font-size: 14px;\">3232</b>名学员提供培训服务 \n 累计观看次数达<b style=\"color:#FFB800;font-size: 14px;\">17090</b>次\n </p> ', 'huanjing.shanhaiyh.com', '', 'http://shiant-oss-common.oss-cn-shenzhen.aliyuncs.com/portal/carousel/98dddcd3-ea07-4b7f-a079-55c0f4639d69.jpg', '1', '2020-06-04 15:10:53', '2020-07-17 14:49:48', '管理员', '管理员', '0');
INSERT INTO `t_sys_carousel` VALUES ('3', '<p>\r\n 已为<b style=\"color:#FFB800;font-size: 14px;\">3232</b>名学员提供培训服务 \r\n 累计观看次数达<b style=\"color:#FFB800;font-size: 14px;\">17090</b>次\r\n </p>', 'jianzhu.shanhaiyh.com', '', 'http://shiant-oss-common.oss-cn-shenzhen.aliyuncs.com/portal/carousel/5208b708-ab97-41a7-8e00-f771a8edf307.jpg', '1', '2020-06-04 16:28:27', '2020-06-04 16:30:26', '管理员', '管理员', '0');
INSERT INTO `t_sys_carousel` VALUES ('4', ' <p>\n 已为<b style=\"color:#FFB800;font-size: 14px;\">3232</b>名学员提供培训服务 \n 累计观看次数达<b style=\"color:#FFB800;font-size: 14px;\">17090</b>次\n </p> ', 'jiaoyu.gynt.shanhaiyh.com', '', 'http://shiant-oss-common.oss-cn-shenzhen.aliyuncs.com/portal/carousel/c629e0fe-ca08-4f05-b762-6731db2d5798.jpg', '1', '2020-06-04 16:44:30', '2020-06-24 14:18:34', '管理员', '管理员', '0');
INSERT INTO `t_sys_carousel` VALUES ('5', '<p>\r\n 已为<b style=\"color:#FFB800;font-size: 14px;\">3232</b>名学员提供培训服务 \r\n 累计观看次数达<b style=\"color:#FFB800;font-size: 14px;\">17090</b>次\r\n </p>', 'ghana.shanhaiyh.com', '', 'http://shiant-oss-common.oss-cn-shenzhen.aliyuncs.com/portal/carousel/52d4076e-feeb-4d62-9dc2-c96ad467b8d8.jpg', '1', '2020-06-04 17:12:54', '2020-06-04 17:12:54', '管理员', '管理员', '0');
INSERT INTO `t_sys_carousel` VALUES ('6', '<p>\r\n 已为<b style=\"color:#FFB800;font-size: 14px;\">3232</b>名学员提供培训服务 \r\n 累计观看次数达<b style=\"color:#FFB800;font-size: 14px;\">17090</b>次\r\n </p>', 'ydyl.shanhaiyh.com', '', 'http://shiant-oss-common.oss-cn-shenzhen.aliyuncs.com/portal/carousel/cbc71646-a338-452f-8ac0-96e757d72ec8.jpg', '1', '2020-06-04 17:29:04', '2020-06-04 17:29:04', '管理员', '管理员', '0');
-- ----------------------------
-- Table structure for t_sys_univers
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_univers`;
CREATE TABLE `t_sys_univers` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
`univers_name` varchar(255) DEFAULT NULL COMMENT '院校名称',
`univers_name_en` varchar(255) DEFAULT NULL COMMENT '英文名称',
`addr_country` varchar(255) NOT NULL COMMENT '所在地(国家)',
`addr_state` varchar(255) NOT NULL COMMENT '所在地(省/州)',
`addr_city` varchar(255) NOT NULL COMMENT '所在地(市)',
`address` varchar(255) DEFAULT NULL COMMENT '所在地(详细地址)',
`Professional_count` int(11) NOT NULL COMMENT '专业数量',
`logo` varchar(500) DEFAULT NULL COMMENT '院校logo',
`introduce` varchar(1000) NOT NULL COMMENT '院校简介',
`nature` varchar(255) NOT NULL COMMENT '院校性质',
`tuition` bigint(20) NOT NULL COMMENT '留学费用',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_sys_univers
-- ----------------------------
INSERT INTO `t_sys_univers` VALUES ('1','加州大学伯克利分校','Berkeley','美国','旧金山','伯克利','市中心','20','','世界大学学术排名第5位','公立','99999');
INSERT INTO `t_sys_univers` VALUES ('2','伦敦大学帝国理工学院','Imperial College','英国','伦敦','南肯辛顿','市中心','20','','直译为伦敦帝国学院','公立','99999');
INSERT INTO `t_sys_univers` VALUES ('3','东京大学','University of Tokyo','日本','东京','大阪','市中心','20','','素质大学','私立','99999');
INSERT INTO `t_sys_univers` VALUES ('4','慕尼黑大学','University of Munich','德国','巴伐利亚','慕尼黑','市中心','20','','世界一流大学','公立','99999');
-- ----------------------------
-- Table structure for t_sys_professional
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_professional`;
CREATE TABLE `t_sys_professional` (
`pro_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
`pro_name` varchar(255) NOT NULL COMMENT '专业名称',
`pro_college` varchar(255) NOT NULL COMMENT '所属学院',
`pro_degree` varchar(255) NOT NULL COMMENT '毕业学位',
`pro_advantage` varchar(20) NOT NULL COMMENT '是否优势专业',
`pro_semester` int(11) NOT NULL COMMENT '学期(月)',
`pro_tuition` bigint(20) NOT NULL COMMENT '学费(¥)',
PRIMARY KEY (`pro_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_sys_professional
-- ----------------------------
INSERT INTO `t_sys_professional` VALUES ('1','生物化学与分子生物学','生物科学学院','工程硕士','是','6','99999');
INSERT INTO `t_sys_professional` VALUES ('2','计算机应用','计算机科学与技术学院','工程硕士','是','6','99999');
INSERT INTO `t_sys_professional` VALUES ('3','生物制药','药理学院','工程硕士','是','6','99999');
-- ----------------------------
-- Table structure for t_sys_organization
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_organization`;
CREATE TABLE `t_sys_organization` (
`or_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '机构编号',
`or_name` varchar(20) NOT NULL COMMENT '机构名称',
`or_Creation_date` varchar(20) NOT NULL COMMENT '创建时间',
`or_intro` varchar(50) DEFAULT NULL COMMENT '机构简介',
`or_logo` varchar(30) DEFAULT NULL COMMENT '机构logo',
`or_country` varchar(30) DEFAULT NULL COMMENT '主攻留学国家',
`or_services` varchar(30) DEFAULT NULL COMMENT '服务领域',
`or_address` varchar(30) DEFAULT NULL COMMENT '详细地址',
`or_hotline` bigint(20) DEFAULT NULL COMMENT '咨询电话',
`or_url` varchar(20) DEFAULT NULL COMMENT '机构网址',
`or_qq` bigint(20) DEFAULT NULL COMMENT '客服QQ',
`or_wechat` varchar(20) DEFAULT NULL COMMENT '客服微信',
`or_wechat_line` varchar(20) DEFAULT NULL COMMENT '微信公众号',
`or_microblog` varchar(20) DEFAULT NULL COMMENT '官方微博',
PRIMARY KEY (`or_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_sys_organization
-- ----------------------------
INSERT INTO `t_sys_organization` VALUES ('1','高科','1999年1月1日','这是一个好机构','','美国','留学金融','三桥','138','www.baidu.com','516','l516','高科公众号','高科微博');
INSERT INTO `t_sys_organization` VALUES ('2','中科','1999年1月1日','这是一个好机构','','美国','留学金融','三桥','138','www.baidu.com','516','l516','高科公众号','高科微博');
INSERT INTO `t_sys_organization` VALUES ('3','低科','1999年1月1日','这是一个好机构','','美国','留学金融','三桥','138','www.baidu.com','516','l516','高科公众号','高科微博');
-- ----------------------------
-- Table structure for t_sys_certification
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_certification`;
CREATE TABLE `t_sys_certification` (
`ce_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '入驻资质编号',
`ce_license` varchar(40) DEFAULT NULL COMMENT '营业执照',
`ce_name` varchar(20) NOT NULL COMMENT '机构联系人',
`ce_id_number` bigint(20) NOT NULL COMMENT '身份证号',
`ce_contact` bigint(20) NOT NULL COMMENT '联系方式',
PRIMARY KEY (`ce_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_sys_certification
-- ----------------------------
INSERT INTO `t_sys_certification` VALUES ('1','','马迈','513646','138');
INSERT INTO `t_sys_certification` VALUES ('2','','马迈','513646','138');
INSERT INTO `t_sys_certification` VALUES ('3','','马迈','513646','138');
| true |
ff2fd64e20c68c83506e22d6a8373b5783ea4166 | SQL | natnoel/Bookstore-Database | /dbLoadBook.sql | UTF-8 | 5,341 | 2.71875 | 3 | [] | no_license | 2011/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* BOOKSHOP */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
INSERT INTO Product VALUES
(1, 23.95, 'Prentice Hall', 'Magnificent colours !!!' );
INSERT INTO Product VALUES
(2, 50.00, 'Wiley', 'Proven in the last to decades UNIX is here to stay. Unix is the backbone of Internet. This book is the best book about Unix ever published');
INSERT INTO Product VALUES
(3, 5.90, 'Wiley', 'The best SQL book ever !!!' );
INSERT INTO Product VALUES
(4, 49.95, 'Oracle', 'This journal soars above and beyond the world of traditional journals' );
INSERT INTO Product VALUES
(5, 8.95, NULL, NULL );
INSERT INTO Product VALUES
(6, 5.00, NULL, NULL );
INSERT INTO Product VALUES
(7, 25.30, 'Andromeda Pty Ltd', 'Very impressive !!!' );
INSERT INTO Product VALUES
(8, 12.56, 'New Impressions', 'This is a dazzling display of vivid orchestral colour and dashing rhytmic exuberance');
INSERT INTO Product VALUES
(9, 10.05, 'Very Heavy Metal Corp.', '... Remarkable, powerful, ... dynamic. ... superior ...' );
INSERT INTO Product VALUES
(10, 15.00, NULL, NULL);
INSERT INTO Keyword VALUES
(1, 'FLOWER');
INSERT INTO Keyword VALUES
(1, 'GARDENING');
INSERT INTO Keyword VALUES
(1, 'COLOUR');
INSERT INTO Keyword VALUES
(2, 'UNIX');
INSERT INTO Keyword VALUES
(2, 'OPERATING SYSTEM');
INSERT INTO Keyword VALUES
(3, 'SQL');
INSERT INTO Keyword VALUES
(4, 'DATABASE');
INSERT INTO Keyword VALUES
(4, 'SQL');
INSERT INTO Keyword VALUES
(7, 'OVERTURE');
INSERT INTO Keyword VALUES
(8, 'SYMPHONY');
INSERT INTO Keyword VALUES
(9, 'SYMPHONY');
INSERT INTO Keyword VALUES
(9, 'ORCHESTRA');
INSERT INTO Keyword VALUES
(10, 'VOYAGER');
INSERT INTO Keyword VALUES
(10, 'STARSHIP');
INSERT INTO Customer VALUES
(100, 'Janusz', 'Getta', 'jrg@cs.uow.edu.au', NULL, 'Australia', 'NSW', 'Wollongong', '2530', 'Barham Pl.', 6, NULL );
INSERT INTO Customer VALUES
(101, 'Kevin', 'Corbley', 'kc@cs.wisc.edu', NULL, 'USA', 'Winsconsin', 'Northpool', 'WI567-23', '234', 4, 6);
INSERT INTO Customer VALUES
(102, 'Ann', 'Boleyn', 'ann@ozemail.coma.au', 610242347819, 'Australia', 'Wagga', '3489',NULL, 'Station', 34, NULL);
INSERT INTO Pbasket VALUES
( TO_DATE('02-APR-2011:10:00', 'DD-MON-YYYY:HH:MI'), TO_DATE('02-APR-2011:10:40', 'DD-MON-YYYY:HH:MI'), 4594567829, 100 );
INSERT INTO Pbasket VALUES
( TO_DATE('12-APR-2011:01:00', 'DD-MON-YYYY:HH:MI'), TO_DATE('12-APR-2011:01:10', 'DD-MON-YYYY:HH:MI'), 1294522229, 101 );
INSERT INTO Pbasket VALUES
( TO_DATE('08-MAY-2011:05:00', 'DD-MON-YYYY:HH:MI'), TO_DATE('08-MAY-2011:05:55', 'DD-MON-YYYY:HH:MI'), 1294522229, 101 );
INSERT INTO Pbasket VALUES
( TO_DATE('16-JAN-2011:06:00', 'DD-MON-YYYY:HH:MI'), TO_DATE('16-JAN-2011:06:15', 'DD-MON-YYYY:HH:MI'), 6781394229, 102 );
INSERT INTO PP VALUES
( TO_DATE('12-APR-2011:01:10', 'DD-MON-YYYY:HH:MI'), 2 );
INSERT INTO PP VALUES
( TO_DATE('08-MAY-2011:05:55', 'DD-MON-YYYY:HH:MI'), 5 );
INSERT INTO PP VALUES
( TO_DATE('08-MAY-2011:05:55', 'DD-MON-YYYY:HH:MI'), 6 );
INSERT INTO PP VALUES
( TO_DATE('08-MAY-2011:05:55', 'DD-MON-YYYY:HH:MI'), 3 );
INSERT INTO PP VALUES
( TO_DATE('08-MAY-2011:05:55', 'DD-MON-YYYY:HH:MI'), 2 );
INSERT INTO PP VALUES
( TO_DATE('16-JAN-2011:06:15', 'DD-MON-YYYY:HH:MI'), 2 );
INSERT INTO PP VALUES
( TO_DATE('16-JAN-2011:06:15', 'DD-MON-YYYY:HH:MI'), 7 );
INSERT INTO PP VALUES
( TO_DATE('16-JAN-2011:06:15', 'DD-MON-YYYY:HH:MI'), 8 );
INSERT INTO PP VALUES
( TO_DATE('16-JAN-2011:06:15', 'DD-MON-YYYY:HH:MI'), 9 );
INSERT INTO PP VALUES
( TO_DATE('16-JAN-2011:06:15', 'DD-MON-YYYY:HH:MI'), 10 );
INSERT INTO Cevaluation VALUES
( 100, 'Excellent !!!', 5, 1 );
INSERT INTO Cevaluation VALUES
( 100, 'Very, very average, nothing special', 2, 2 );
INSERT INTO Cevaluation VALUES
( 102, 'Magnificent', 5, 10 );
INSERT INTO Book VALUES
(18752020860, 'Flowers by Colour', 'Weldon Russel Pty. Ltd.', 1990, 'Flowers by Colour is a comprehensive guide to more than 1,000 popular garden flower', 'OTHER', 1 );
INSERT INTO Book VALUES
(12224602080, 'Unix for cops', 'Prentice Hall Pty. Ltd.', 2007, 'This is an ultimate Unix manual', 'COMPUTER', 2 );
INSERT INTO Book VALUES
(12755520369, 'SQL for 2nd year students', 'Morgan Kaufman', 2006, 'Comprehensive SQL guide', 'COMPUTER', 3 );
INSERT INTO Author VALUES
(18752020860, 'Valerie', 'Swan');
INSERT INTO Author VALUES
(12224602080, 'Keith', 'Morgan');
INSERT INTO Author VALUES
(12224602080, 'Mark', 'Thornthwaite');
INSERT INTO Author VALUES
(12755520369, 'Edgar', 'Codd');
INSERT INTO Journal VALUES
(77520368899, 'Oracle Magazine', 'Oracle Publishers', 4 );
INSERT INTO Jissue VALUES
(77520368899, 8, 4, 5 );
INSERT INTO Jissue VALUES
(77520368899, 8, 5, 6 );
INSERT INTO CDROM VALUES
( 7, 'Romeo and Juliet, Fantasy Overture', 'Crystal Collection', 1986, 'CLASSIC' );
INSERT INTO CDROM VALUES
( 8, 'Tchaikovsky Symphony no. 1', 'Crystal Collection', 1989, 'CLASSIC' );
INSERT INTO CDROM VALUES
( 9, 'Tchaikovsky Symphony no. 2', 'Telarc', 1990, 'CLASSIC' );
INSERT INTO Video VALUES
(10, 'Startrek Voyager', 'Columbia', 1997, 'SCIENCE FICTION' );
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
| true |
940ff7d8d4b8f7534289d62d8f6babf810620517 | SQL | unbeman/intern_task | /sql/init_001.sql | UTF-8 | 1,568 | 3.765625 | 4 | [] | no_license | create database shop;
\connect shop;
create table if not exists companies
(
id serial not null
constraint companies_pkey
primary key,
title varchar not null,
description varchar
)
;
alter table companies owner to postgres
;
create table if not exists tags
(
id serial not null
constraint tags_pkey
primary key,
title varchar not null,
constraint tags_title_id_key
unique (title, id)
)
;
alter table tags owner to postgres
;
create table if not exists workers
(
id serial not null
constraint workers_pkey
primary key,
full_name varchar not null,
position varchar not null,
phone_number varchar not null,
fk_company_id integer
constraint workers_fk_company_id_fkey
references companies
)
;
alter table workers owner to postgres
;
create table if not exists goods
(
id serial not null
constraint goods_pkey
primary key,
title varchar not null,
description varchar,
price integer not null,
counts integer,
fk_worker_id integer
constraint goods_fk_worker_id_fkey
references workers,
fk_company_id integer
constraint goods_fk_company_id_fkey
references companies,
constraint goods_title_fk_company_id_key
unique (title, fk_company_id)
)
;
alter table goods owner to postgres
;
create table if not exists tags_to_goods
(
tag_id integer not null
constraint tags_to_goods_tag_id_fkey
references tags,
goods_id integer not null
constraint tags_to_goods_goods_id_fkey
references goods,
constraint tags_to_goods_pkey
primary key (tag_id, goods_id)
)
;
alter table tags_to_goods owner to postgres
; | true |
7aab51108d216677732f6bbe8b8662af43bc9b74 | SQL | zengamer21/POST_Grad | /scripts/create_db_2.sql | UTF-8 | 2,672 | 3.71875 | 4 | [] | no_license | -- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema post_grad
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema post_grad
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `post_grad` DEFAULT CHARACTER SET utf8 ;
USE `post_grad` ;
-- -----------------------------------------------------
-- Table `post_grad`.`persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `post_grad`.`persons` (
`id` INT NOT NULL,
`charger_id` VARCHAR(45) NULL,
`first_name` VARCHAR(45) NULL,
`middle_name` VARCHAR(45) NULL,
`last_name` VARCHAR(45) NULL,
`pos_approved` TINYINT NULL,
`pos_completed` TINYINT NULL,
`role` VARCHAR(45) NULL,
`address_street` VARCHAR(100) NULL,
`address_city` VARCHAR(100) NULL,
`address_state` VARCHAR(100) NULL,
`address_zip` VARCHAR(5) NULL,
`advisor_id` INT NULL,
`phone` VARCHAR(45) NULL,
`email` VARCHAR(100) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `post_grad`.`courses`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `post_grad`.`courses` (
`id` INT NOT NULL,
`crn` VARCHAR(10) NULL,
`course_num` VARCHAR(10) NULL,
`title` VARCHAR(35) NULL,
`credit` DOUBLE NULL,
`semester` VARCHAR(45) NULL,
`instructor` VARCHAR(100) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `post_grad`.`StudentsCourses`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `post_grad`.`StudentsCourses` (
`id` INT NOT NULL,
`grade` VARCHAR(2) NULL,
`persons_id` INT NOT NULL,
`courses_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_StudentsCourses_persons1_idx` (`persons_id` ASC),
INDEX `fk_StudentsCourses_courses1_idx` (`courses_id` ASC),
CONSTRAINT `fk_StudentsCourses_persons1`
FOREIGN KEY (`persons_id`)
REFERENCES `post_grad`.`persons` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_StudentsCourses_courses1`
FOREIGN KEY (`courses_id`)
REFERENCES `post_grad`.`courses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
| true |
fab7acd42969b9f383a2c31089482483d3755dc0 | SQL | Daniel-Droppa/employee-tracker | /employee_db.sql | UTF-8 | 2,606 | 4.40625 | 4 | [] | no_license | -- DROP DATABASE IF EXISTS employeeTracker_DB;
-- CREATE DATABASE employeeTracker_DB;
-- USE employeeTracker_DB;
DROP DATABASE IF EXISTS employee_db;
CREATE DATABASE employee_db;
USE employee_db;
CREATE TABLE departments (
DeptID INTEGER,
dep_name VARCHAR(30),
PRIMARY KEY (DeptID)
);
CREATE TABLE roles (
rolesId INTEGER AUTO_INCREMENT NOT NULL,
title VARCHAR(30),
salary DECIMAL,
-- FOREIGN KEY (DeptID) REFERENCES departments(DeptID),
PRIMARY KEY (rolesId)
);
CREATE TABLE employees (
id INTEGER AUTO_INCREMENT NOT NULL,
full_name VARCHAR(30),
roles VARCHAR(30),
-- FOREIGN KEY (rolesId ) REFERENCES roles(rolesId),
is_manager BOOLEAN DEFAULT FALSE,
manager VARCHAR(30),
PRIMARY KEY (id)
);
INSERT INTO roles (title, salary)
VALUES ('Sales Person', 55000), ('Accountant', 12000),('Software Engineer', 85000),('Front End Developer', 75000), ('Back End Developer',85000),('Lawyer',120000);
INSERT INTO departments (dep_name)
VALUES ('Sales'), ('Finance'), ('Development'), ('Legal');
-- SELECT * FROM employees;
SELECT * FROM employees;
SELECT * FROM roles;
SELECT id, full_name, roles, salary, manager FROM
employees LEFT JOIN roles
ON employees.roles = roles.title;
SELECT id, full_name, dep_name FROM
employees RIGHT JOIN departments
ON employees.roles = roles.title;
-- DROP DATABASE IF EXISTS employee_db;
-- CREATE DATABASE employee_db;
-- USE employee_db;
-- CREATE TABLE department(
-- id INT PRIMARY KEY AUTO_INCREMENT,
-- name VARCHAR(30) NOT NULL
-- );
-- CREATE TABLE roles(
-- id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
-- title VARCHAR (30),
-- salary DECIMAL NOT NULL,
-- department_id INT NOT NULL,
-- CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES department(id)
-- );
-- CREATE TABLE employee(
-- id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-- first_name VARCHAR(30) NOT NULL,
-- last_name VARCHAR(30) NOT NULL,
-- roles_id INT NOT NULL,
-- CONSTRAINT fk_roles FOREIGN KEY (roles_id) REFERENCES roles(id),
-- -- manager VARCHAR(30),
-- manager_id INT,
-- CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employee(id)
-- );
-- SELECT * FROM department;
-- SELECT * FROM roles;
-- SELECT * FROM employee;
-- INSERT INTO department (name)
-- VALUES ("Sales"), ("Engineering"), ("Finance"), ("Legal");
-- INSERT INTO roles (title, salary, department_id)
-- VALUES ("Sales Lead", 100000, 1),
-- ("Salesperson", 80000, 1),
-- ("Lead Engineer", 150000, 2),
-- ("Software Engineer", 120000, 2),
-- ("Accountant", 125000, 3),
-- ("Lead Lawyer", 190000, 4),
-- ("Lawyer", 130000, 4);
| true |
9199265c742d789050b54c3ddb9477b9354add71 | SQL | caio-cunha/hiring | /Caio/cliente_xl.sql | UTF-8 | 1,404 | 3.078125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: 10-Jun-2020 às 15:23
-- Versão do servidor: 10.1.38-MariaDB
-- versão do PHP: 7.3.2
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: `cliente_xl`
--
CREATE DATABASE IF NOT EXISTS `cliente_xl` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `cliente_xl`;
-- --------------------------------------------------------
--
-- Estrutura da tabela `inventario`
--
CREATE TABLE `inventario` (
`id` int(10) NOT NULL,
`modelo` varchar(100) NOT NULL,
`fabricante` varchar(100) NOT NULL,
`estoque` int(10) NOT NULL,
`preco_unitario` double(10,2) NOT NULL,
`modalidade_venda` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `inventario`
--
ALTER TABLE `inventario`
ADD PRIMARY KEY (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
aaddd35cd36081986e65c35c70a28b0590fd541d | SQL | ptomulik/veetou | /share/oracle/packages/veetou/tables/ko/ko_missing_protos_j.ddl | UTF-8 | 1,274 | 3.15625 | 3 | [] | no_license | CREATE TABLE v2u_ko_missing_protos_j
OF V2u_Ko_Missing_Proto_J_t
(
-- PK
CONSTRAINT v2u_ko_missing_protos_j_pk
PRIMARY KEY ( student_id
, subject_id
, specialty_id
, semester_id
, classes_type
, job_uuid
)
-- FK
, CONSTRAINT v2u_ko_missing_protos_j_f0
FOREIGN KEY (job_uuid)
REFERENCES v2u_ko_jobs(job_uuid)
, CONSTRAINT v2u_ko_missing_protos_j_f1
FOREIGN KEY (subject_id, job_uuid)
REFERENCES v2u_ko_subjects(id, job_uuid)
, CONSTRAINT v2u_ko_missing_protos_j_f2
FOREIGN KEY (specialty_id, job_uuid)
REFERENCES v2u_ko_specialties(id, job_uuid)
, CONSTRAINT v2u_ko_missing_protos_j_f3
FOREIGN KEY (semester_id, job_uuid)
REFERENCES v2u_ko_semesters(id, job_uuid)
, CONSTRAINT v2u_ko_missing_protos_j_f4
FOREIGN KEY (subject_id, specialty_id, semester_id, job_uuid)
REFERENCES v2u_ko_subject_semesters_j(subject_id, specialty_id, semester_id, job_uuid)
)
OBJECT IDENTIFIER IS PRIMARY KEY
;
/
-- vim: set ft=sql ts=4 sw=4 et:
| true |
6ff67a8e1c65e6dbc3a8bdc9b8d3d0050882d735 | SQL | wbband/OA | /SMT.Workflow/SourceCode/SMT.SaaS.FlowSystem/WFTools/DB/Tracking/MySql/StoredProcedures/InsertTrackingDataItem.sql | UTF-8 | 1,083 | 3.390625 | 3 | [] | no_license | DELIMITER $$
DROP PROCEDURE IF EXISTS InsertTrackingDataItem $$
/*
* Insert a single tracking data item
*/
CREATE PROCEDURE InsertTrackingDataItem
(
IN p_WORKFLOW_INSTANCE_ID BIGINT UNSIGNED
,IN p_EVENT_ID BIGINT UNSIGNED
,IN p_EVENT_TYPE CHAR(1)
,IN p_FIELD_NAME VARCHAR(256)
,IN p_TYPE_FULL_NAME VARCHAR(128)
,IN p_ASSEMBLY_FULL_NAME VARCHAR(256)
,IN p_DATA_STR LONGTEXT
,IN p_DATA_BLOB BLOB
,IN p_DATA_NON_SERIALISABLE BOOLEAN
,OUT p_TRACKING_DATA_ITEM_ID BIGINT UNSIGNED
)
sproc:BEGIN
DECLARE l_FIELD_TYPE_ID BIGINT UNSIGNED;
CALL GetTypeId(l_FIELD_TYPE_ID, p_TYPE_FULL_NAME, p_ASSEMBLY_FULL_NAME, NULL);
INSERT INTO TRACKING_DATA_ITEM
(
WORKFLOW_INSTANCE_ID
,EVENT_ID
,EVENT_TYPE
,FIELD_NAME
,FIELD_TYPE_ID
,DATA_STR
,DATA_BLOB
,DATA_NON_SERIALISABLE
)
VALUES
(
p_WORKFLOW_INSTANCE_ID
,p_EVENT_ID
,p_EVENT_TYPE
,p_FIELD_NAME
,l_FIELD_TYPE_ID
,p_DATA_STR
,p_DATA_BLOB
,p_DATA_NON_SERIALISABLE
);
SET p_TRACKING_DATA_ITEM_ID = LAST_INSERT_ID();
END $$
DELIMITER ;
| true |
ac4911c7749c5e2bbabd729f68ad40aac952e166 | SQL | Roozbeh-Bazargani/Database-HW | /HW2/main.sql | UTF-8 | 4,367 | 4.40625 | 4 | [] | no_license | CREATE TABLE Actor
(
actor_id INT,
first_name VARCHAR(255),
last_name VARCHAR(255),
country VARCHAR(255),
age INT,
gender ENUM('female', 'male', 'other') NOT NULL,
PRIMARY KEY (actor_id)
);
CREATE TABLE Movie
(
movie_id INT,
title VARCHAR(255),
genre VARCHAR(255),
PRIMARY KEY (movie_id)
);
CREATE TABLE Cinema
(
cinema_id INT,
name VARCHAR(255),
PRIMARY KEY (cinema_id)
);
CREATE TABLE Actedin
(
id INT,
actor_id INT,
movie_id INT,
PRIMARY KEY (id),
FOREIGN KEY (actor_id) REFERENCES Actor (actor_id),
FOREIGN KEY (movie_id) REFERENCES Movie (movie_id)
);
CREATE TABLE Playedin
(
id INT,
cinema_id INT,
movie_id INT,
ticket_price INT,
date DATETIME NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (cinema_id) REFERENCES Cinema (cinema_id),
FOREIGN KEY (movie_id) REFERENCES Movie (movie_id)
);
CREATE TABLE Viewer
(
viewer_id INT,
first_name VARCHAR(255),
last_name VARCHAR(255),
age INT,
gender ENUM('female', 'male', 'other') NOT NULL,
PRIMARY KEY (viewer_id)
);
CREATE TABLE Attended
(
id INT,
Playedin_id INT,
viewer_id INT,
PRIMARY KEY (id),
FOREIGN KEY (Playedin_id) REFERENCES Playedin (id),
FOREIGN KEY (viewer_id) REFERENCES Viewer (viewer_id)
);
-- 01 ---------- OK
SELECT MAX(ticket_price)
FROM Playedin
WHERE cinema_id IN (
SELECT cinema_id
From Cinema
WHERE name="Esteghlal")
-- 02 ---------- OK
SELECT name
FROM Cinema
WHERE cinema_id IN (
SELECT cinema_id
FROM Playedin
GROUP BY cinema_id
HAVING min(ticket_price) >= 30)
ORDER BY name
-- 03 ---------- !!!!!
WITH Leila(actor_id) AS (
SELECT actor_id
FROM Actor
WHERE first_name="Leila" AND last_name="Hatami")
SELECT title
FROM Movie
WHERE movie_id IN (
SELECT movie_id
FROM Actedin
WHERE actor_id = Leila)
AND
movie_id IN (
SELECT movie_id
FROM Playedin
WHERE cinema_id = (
SELECT cinema_id
FROM Cinema
WHERE name = "Ghods"))
-- 04 ---------- OK
SELECT first_name, last_name
FROM Viewer
WHERE gender="male" AND age=(
SELECT max(age)
FROM Viewer
WHERE gender="male")
-- 05 --------------
WITH FILMID(movie_id) AS (
SELECT movie_id
FROM Movie
WHERE name="Tenet"),
A(viewer_id) AS (
SELECT viewer_id
FROM Attended
WHERE Playedin_id IN (
SELECT id
FROM Playedin
WHERE movie_id=FILMID.movie_id))
SELECT avg(age)
FROM Viewer
WHERE viewer_id IN A
-- 06 --------------
WITH PLAYID(id) AS (
SELECT id
FROM Playedin
WHERE ticket_price=20 AND date.year=2000)
SELECT first_name, last_name
FROM Viewer
WHERE viewer_id IN (
SELECT viewer_id
FROM Attended
WHERE Playedin_id IN PLAYID)
ORDER BY last_name, first_name
-- 07 -------------- OK
SELECT first_name, last_name
FROM Actor
WHERE actor_id IN (
SELECT actor_id
FROM Actedin
WHERE movie_id IN (
SELECT movie_id
FROM Movie
WHERE genre="Comedy"))
ORDER BY last_name, first_name
-- 08 -------------- OK
SELECT SUM(ticket_price)
FROM Playedin AS P JOIN Attended AS A on p.id=A.Playedin_id
WHERE P.cinema_id IN (
SELECT cinema_id
From Cinema
WHERE name="Ghods")
--09 -------------
WITH DATEID(id) AS (
SELECT id
FROM Playedin
WHERE date.year=2010)
SELECT DISTINCT first_name, last_name
FROM Viewer
WHERE viewer_id IN (
SELECT viewer_id
FROM Attended
WHERE Playedin_id IN PLAYID)
ORDER BY last_name, first_name
--10 -------------
WITH DRIVE(movie_id) AS (
SELECT movie_id
FROM Movie
WHERE title="Drive")
SELECT COUNT(*), gender
FROM Viewer
WHERE gender IN {"male", "female"} AND viewer_id IN (
SELECT DISTINCT viewer_id
FROM Attended
WHERE Playedin_id IN (
SELECT id
FROM Playedin
WHERE movie_id = DRIVE))
GROUP BY gender
--11 ------------- !!!!!
SELECT title
FROM Movie
WHERE movie_id IN (
SELECT movie_id
FROM Playedin
WHERE id IN(
SELECT Playedin_id
FROM Attended
WHERE COUNT(viewer_id)=1))
ORDER BY title
--12 -------------
--13 -------------
SELECT title, COUNT(*) AS NUMBER
FROM (Movie AS M NATURAL JOIN Playedin AS P) JOIN Attended on P.id=Playedin_id
GROUP BY M.movie_id
ORDER BY NUMBER
???????
--14 -------------
--15 -------------
| true |
d91b58cf2a49496a0396db31e5ab451bf893a5ee | SQL | leezzx/MySQL-Practice | /3.sql | UTF-8 | 4,141 | 4.34375 | 4 | [] | no_license | CREATE TABLE city2 SELECT * FROM city; # city 테이블과 똑같은 city2 테이블 생성
SELECT * FROM city2;
CREATE DATABASE suan; # 새로운 데이터 베이스를 생성, USE문으로 새 데이터베이스 사용
USE suan;
# 우클릭 REFRESH ALL을 통해 새로고침 가능
SELECT * FROM test; # Table 우클릭 CREATE TABLE을 통해 테이블 생성 가능, 데이터 타입 : https://dev.mysql.com/doc/refman/8.0/en/data-types.html
CREATE TABLE test2 ( # Table 직접 생성
id INT NOT NULL PRIMARY KEY, # NULL 비허용
col1 INT NULL, # NULL 허용
col2 FLOAT NULL,
col3 VARCHAR(45) NULL
);
SELECT * FROM test2;
ALTER TABLE test2
ADD col4 INT NULL; # ALTER TABLE과 ADD를 통해 테이블에 컬럼추가 가능
SELECT * FROM test2;
ALTER TABLE test2
MODIFY col4 VARCHAR(20) NULL; # ALTER TABLE과 MODIFY를 통해 테이블의 컬럼 타입을 변경가능
DESC test2;
ALTER TABLE test2
DROP col4; # ALTER TABLE과 DROP을 사용하여 테이블의 컬럼 제거 가능
# 인덱스(index) : 테이블에서 원한는 데이터를 빠르게 찾기 위해 사용, 테이블 컬럼 수정시 인덱스도 같이 수정해야함, 인덱스가 있는 테이블의 처리속도 감소
CREATE INDEX Col1Idx # 인덱스 생성
ON test (col1);
SHOW INDEX FROM test; # 인덱스 정보 보기
CREATE UNIQUE INDEX Col2Idx # 중복값을 허용하지 않는 인덱스
ON test (col2);
SHOW INDEX FROM test;
ALTER TABLE test
ADD FULLTEXT Col3Ix(col3); # 일반적인 인덱스와 달리 매우 빠르게 테이블의 모든 텍스트 칼럼을 검색
SHOW INDEX FROM test;
ALTER TABLE test
DROP INDEX Col3Idx; # ALTER TABLE ... DROP을 이용한 인덱스 삭제
DROP INDEX Col2Idx ON test; # DROP을 이용한 인덱스 삭제
/* VIEW : 데이터베이스에 존재하는 가상 테이블, 행과 열은 가지고 있지만 실제로 데이터를 저장하지는 않음, 여러 테이블이나 뷰를 하나의 테이블 처럼 볼 수 있음
다른 테이블이나 뷰에 저장되어 있는 데이터를 보여주는 역할만 수행, 한 번 정의된 뷰는 변경 불가, 자신만의 인덱스를 가질 수 없음, 쿼리 재사용 가능 */
CREATE VIEW testView AS
SELECT Col1, Col2
FROM test; # Col1과 Col2를 지니는 VIEW 만들기
SELECT * FROM testView;
ALTER VIEW testView AS
SELECT Col1, Col2, Col3
FROM test; # ALTER문 사용하여 뷰를 수정
SELECT * FROM testView;
DROP VIEW testView; # VIEW 삭제
# city, country, countrylanguage 테이블을 JOIN하고, 한국에 대한 정보만 뷰 생성하기
USE world;
CREATE VIEW allView AS
SELECT city.Name, country. SurfaceArea, city.Population, countrylanguage.Language
FROM city
JOIN country ON city.CountryCode = country.Code
JOiN countrylanguage ON city.CountryCode = countrylanguage.CountryCode
WHERE city.CountryCode = 'KOR';
SELECT * FROM allView;
USE suan;
INSERT INTO test
VALUE(1, 123, 1.1, "Test"); # 테이블 이름 다음에 나오는 열 생략가능, 생략 시 VALUE 다음에 나오는 값들의 순서 및 개수가 테이블에 정의된 열 순서 및 개수와 동일해야 함
SELECT * FROM test;
# 테이블 상에 직접 입력 후 Apply를 통해 가능alter
INSERT INTO test2 SELECT * FROM test; # test 테이블에 있는 내용을 test2 테이블에 복사
SELECT * FROM test2;
UPDATE test # 기존에 입력되어 있는 값 변경하는 구문
SET col1 = 1, col2 = 1.0, col3 = 'test'
WHERE id = 1; # WHERE 생략 가능하나 그 경우 테이블 전체 행의 내용 변경
SELECT * FROM test;
DELETE FROM test # 행 단위로 데이터 삭제하는 구문, 데이터는 지워지지만 테이블 용량은 줄지 않음(롤백 가능하기 때문), 원하는 데이터만 지울 수 있음
WHERE id = 1;
SELECT * FROM test;
TRUNCATE TABLE test; # 용량이 줄어들고 인덱스 등도 모두 삭제, 테이블은 삭제하지 않고 데이터만 삭제, 한꺼번에 다 지워야 함, 삭제 후 절대 복구 불가
SELECT * FROM test;
DROP TABLE test; # 테이블 전체를 삭제, 공간, 객체를 삭제, 되돌리기 불가능
DROP DATABASE suan; # 해당 데이터베이스를 삭제 | true |
de00661b5076c8288241f33e6e78e79cc38ee63d | SQL | radigost/managers2 | /migrations/20170423001.sql | UTF-8 | 1,000 | 3.625 | 4 | [] | no_license | -- UPDATE managers_node mn set category=
-- case when category ='npc' THEN 'player'
-- when category ='player' then 'npc'
-- end;
--
alter table managers_node add COLUMN text TEXT default '';
UPDATE managers_node mn
set text = (
SELECT DISTINCT text from managers_node_choice mnc where mnc.to_node_id=mn.id
);
alter table managers_node_choice drop COLUMN text;
ALTER TABLE public.managers_node_choice
DROP CONSTRAINT managers_node_choice_from_node_id_178b415a_fk_managers_node_id;
ALTER TABLE public.managers_node_choice
ADD CONSTRAINT managers_node_choice_from_node_id_178b415a_fk_managers_node_id
FOREIGN KEY (from_node_id) REFERENCES managers_node (id) ON DELETE CASCADE ;
ALTER TABLE public.managers_node_choice
DROP CONSTRAINT managers_node_choice_to_node_id_5865f372_fk_managers_node_id;
ALTER TABLE public.managers_node_choice
ADD CONSTRAINT managers_node_choice_to_node_id_5865f372_fk_managers_node_id
FOREIGN KEY (to_node_id) REFERENCES managers_node(id) ON DELETE CASCADE ; | true |
46dd896826fd6b0436ea62300792933c56d03e49 | SQL | ivangp61/MMM_CVS | /Database/CVS/SQL Server Scripts1/UAT.sql | UTF-8 | 8,757 | 3.234375 | 3 | [] | no_license | SELECT MAX(MC.JobLoadDate)
FROM EnterpriseHub.dbo.MemberCompany MC
WHERE MC.JobLoadDate =
with CVSCAG as
(
SELECT [BenefitPkgXRefId]
,[Carrier]
,[Account]
,[GroupNumber]
,[GroupName]
,[Bin]
,[RxPCN]
,[RxGroup]
,[MatchOn]
,[SentFile]
FROM [EnterpriseHub].[CVS].[Cag]
WHERE [Carrier] IS NOT NULL
AND [Carrier] LIKE '8%'
UNION
SELECT C.BenefitPkgXRefId
,SecCarrier AS [Carrier]
,SecAccount AS [Account]
,SecGroupNumber AS [GroupNumber]
,SecGroupName AS [GroupName]
,[Bin]
,[RxPCN]
,[RxGroup]
,[MatchOn]
,[SentFile]
FROM [EnterpriseHub].[CVS].[Cag] C
WHERE SecCarrier IS NOT NULL
AND SecCarrier LIKE '3%'
)
SELECT *
FROM CVSCag CAG
WHERE CAG.[BenefitPkgXRefId] IN(410,408)
;
select mi.*
from EnterpriseHub.dbo.MemberIndicator MI
inner join EnterpriseHub.dbo.MemberCompany MC
on MI.MemberRecId = MC.MemberRecId
and MI.IndMRefId = 24
and (ISNULL(MI.IndEndDate,GETDATE()) >= '01/01/2014')
INNER JOIN EnterpriseHub.XRef.BenefitPackage BP ON BP.SORId = MI.IndValue
--INNER JOIN CVSCag CAG ON CAG.[BenefitPkgXRefId] = BP.[BenefitPkgXRefId]
where 1=1
and mc.MemberRecId = 502751
;
SELECT XBP.*
FROM MRef.BenefitPackage MBP
INNER JOIN Xref.BenefitPackage XBP
ON MBP.BenefitPkgMRefId = XBP.BenefitPkgMRefId
WHERE XBP.ExternalValue IN('P00310749499', 'P00310749643')
select mi.*
from EnterpriseHub.dbo.MemberIndicator MI
inner join EnterpriseHub.dbo.MemberCompany MC
on MI.MemberRecId = MC.MemberRecId
and MI.IndMRefId = 24
and (ISNULL(MI.IndEndDate,GETDATE()) >= '01/01/2014')
INNER JOIN EnterpriseHub.XRef.BenefitPackage BP ON BP.SORId = MI.IndValue
INNER JOIN CVSCag CAG ON CAG.[BenefitPkgXRefId] = BP.[BenefitPkgXRefId]
where 1=1
and mc.MemberRecId = 42730
;
--=================MEMBER_KEYS==========
SELECT *
FROM EnterpriseHub.mref.ExternalType ET
;
SELECT TOP 100 M.MemberRecId, M.FirstName, M.JobLoadDate, xm.ExternalValue, ET.Code, ET.[Desc]
FROM EnterpriseHub.dbo.MemberCompany M
INNER JOIN EnterpriseHub.Xref.Member XM
ON M.MemberRecId = XM.MemberRecId AND M.CompanyMRefId = XM.CompanyMRefId
INNER JOIN EnterpriseHub.mref.ExternalType ET
ON XM.ExternalTypeMRefId = ET.ExternalTypeMRefId --AND ET.Code = 'MP'
WHERE XM.ExternalValue = '010054917'--'010596746'--'N00255066648'
M.MemberRecId IN(112334)--112334)--10029)--)--301559)
;
--=================MEMBER_KEYS==========
SELECT *
FROM ENTERPRISEINTERFACES.CVS.PREGNANCYCOVEREDPLAN P
--WHERE P.
SELECT CS.AvetaID, CS.MemberID, CS.[Group], CS.ST_Group, CS.FirstName, CS.LastName, CS.IndValue
FROM EnterpriseInterfaces.CVS.CVSSqeletonLayout CS
WHERE 1 = 1
AND avetaid = '010585502'--'010623740'--'030075420'
AND INDVALUE IN('P00310749643','P00310749499')
--AND PREGNANCYCODE = 'Y'
;
SELECT DISTINCT CS.AvetaID, CS.MemberID, CS.[Group], CS.ST_Group, CS.FirstName, CS.LastName, CS.IndValue, C.ClaimRefID
FROM EnterpriseInterfaces.CVS.CVSSqeletonLayout CS
INNER JOIN ENTERPRISEINTERFACES.CVS.PREGNANCYCOVEREDPLAN AS PREG
ON CS.INDVALUE = PREG.BENEFITPACKAGEID
INNER JOIN ENTERPRISEHUB.DBO.CLAIM AS C
ON CS.MEMBERID = C.SubscriberMemberMRefID
WHERE 1 = 1
AND avetaid = '010054917'--'010623740'--'030075420'
AND INDVALUE IN('P00310749643','P00310749499')
AND C.ServiceDateFrom >= dateadd(month,-9, GETDATE()) --Claims in the last 9 months
AND C.ClaimStatusCodeMRefID not in (5,13)
--AND PREGNANCYCODE = 'Y'
;
SELECT *
FROM EnterpriseInterfaces.CVS.PregnancyAndNewBornCodes p
WHERE P.ISNEWBORNCODE <> 1
;
SELECT TOP 100 *
FROM ENTERPRISEHUB.DBO.CLAIM C
WHERE C.ClaimRefID = 6262256
;
SELECT DISTINCT CS.AvetaID, CS.MemberID, CS.[Group], CS.ST_Group, CS.FirstName, CS.LastName, CS.IndValue, C.ClaimRefID, C.ServiceDateFrom, C.ServiceDateTo, CD.DiagnosisCodeMRefId, CODE.DiagnosisCode
FROM EnterpriseInterfaces.CVS.CVSSqeletonLayout CS
INNER JOIN ENTERPRISEINTERFACES.CVS.PREGNANCYCOVEREDPLAN AS PREG
ON CS.INDVALUE = PREG.BENEFITPACKAGEID
INNER JOIN ENTERPRISEHUB.DBO.CLAIM AS C
ON CS.MEMBERID = C.SUBSCRIBERMEMBERMREFID
LEFT JOIN EnterpriseHub.dbo.ClaimDiagnosis CD
ON CD.ClaimRefID = C.ClaimRefID
LEFT JOIN EnterpriseHub.MRef.DiagnosisCode CODE
ON CODE.DiagnosisCodeMrefId = CD.DiagnosisCodeMRefId
INNER JOIN ENTERPRISEINTERFACES.CVS.PREGNANCYANDNEWBORNCODES AS P
ON P.CODE = CODE.DIAGNOSISCODE
WHERE 1 = 1
AND avetaid = '010054917 '--'010585502'
AND INDVALUE IN('P00310749643','P00310749499')
AND CODE.DiagnosisCode IS NOT NULL
AND C.ServiceDateFrom >= dateadd(month,-9, GETDATE()) --Claims in the last 9 months
AND C.ClaimStatusCodeMRefID not in (5,13)
--AND P.ISNEWBORNCODE <> 1
--AND PREGNANCYCODE = 'Y'
AND C.ClaimRefID = 73739834
AND CD.DiagnosisCodeMRefId = 99685
;
--=======================================TEST_CASES============================
update EnterpriseHub.dbo.MemberCompany
set birthdate = '1957-09-27 00:00:00.000'
WHERE MemberRecId = 112334
;
SELECT *
FROM ENTERPRISEHUB.DBO.CLAIM C
WHERE C.ClaimRefID = 73739834
;
--UPDATE ENTERPRISEHUB.DBO.CLAIM
SET ServiceDateFrom = '2017-04-21', --'2016-09-21'--
ServiceDateTo = '2017-04-21'
WHERE
--SubscriberMemberMRefID = 301559
--AND
ClaimRefID = 73957863
;
SELECT *
FROM EnterpriseHub.dbo.ClaimDiagnosis D
WHERE D.ClaimRefID = 73739834
AND D.DiagnosisCodeMRefId = 99685
;
--UPDATE EnterpriseHub.dbo.ClaimDiagnosis
SET DiagnosisCodeMRefId = 7545
WHERE ClaimRefID = 73957863
AND DiagnosisCodeMRefId = 28697
;
--=======================================TEST_CASES============================
--=======================================TEST_CASES============================
SELECT *
FROM ENTERPRISEHUB.DBO.CLAIM C
WHERE C.ClaimRefID = 73331710
;
--UPDATE ENTERPRISEHUB.DBO.CLAIM
SET ServiceDateFrom = '2017-04-21', --'2016-09-21'--
ServiceDateTo = '2017-04-21'
WHERE
--SubscriberMemberMRefID = 301559
--AND
ClaimRefID = 73739834
;
SELECT *
FROM EnterpriseHub.dbo.ClaimDiagnosis D
WHERE D.ClaimRefID = 73331710
AND D.DiagnosisCodeMRefId = 32162
;
--UPDATE EnterpriseHub.dbo.ClaimDiagnosis
SET DiagnosisCodeMRefId = 8961
WHERE ClaimRefID = 76258002
AND DiagnosisCodeMRefId = 25163
;
--=======================================TEST_CASES============================
SELECT TOP 100 *
FROM EnterpriseHub.MRef.DiagnosisCode D
WHERE DIAGNOSISCODE = '676.94'--'633.10'
SELECT DISTINCT TOP 100 C.ClaimRefID, c.ServiceDateFrom, C.ServiceDateTo
FROM ENTERPRISEHUB.DBO.CLAIM c
WHERE C.ClaimRefID in(73957863), 73739834)
SELECT DISTINCT TOP 100 C.ClaimRefID, c.ServiceDateFrom, C.ServiceDateTo
FROM ENTERPRISEHUB.DBO.CLAIM AS C
WHERE C.ClaimRefID in(73331710, 73739834)
--CRefId: 73739834
--Diag:99685
--ServDate:2016-04-21 00:00:00.000
--:633.10:
--2017-04-21 00:00:00.000
--73331710:32162:2016-03-22 00:00:00.000:676.94
SELECT C.ClaimRefID, C.BenefitPkgRecId, C.SubscriberMemberMRefID, CODE.DiagnosisCodeMRefID, CODE.DiagnosisCode
FROM ENTERPRISEHUB.DBO.CLAIM AS C
LEFT OUTER JOIN
ENTERPRISEHUB.DBO.CLAIMDIAGNOSIS AS CD
ON CD.CLAIMREFID = C.CLAIMREFID
LEFT OUTER JOIN
ENTERPRISEHUB.MREF.DIAGNOSISCODE AS CODE
ON CODE.DIAGNOSISCODEMREFID = CD.DIAGNOSISCODEMREFID
WHERE C.CLAIMREFID = 73957863
AND C.CLAIMSTATUSCODEMREFID NOT IN (5, 13)
;
SELECT *
FROM ENTERPRISEHUB.Xref.BenefitPackage XBP
SELECT XBP.*
FROM ENTERPRISEHUB.MRef.BenefitPackage MBP
INNER JOIN ENTERPRISEHUB.Xref.BenefitPackage XBP
ON MBP.BenefitPkgMRefId = XBP.BenefitPkgMRefId
WHERE XBP.ExternalValue IN('P00310749499', 'P00310749643')
SELECT TOP 100 CV.[Group], CV.[ST_Group], CV.PregnancyCode
FROM ENTERPRISEINTERFACES.CVS.CVSSQELETONLAYOUT AS CV
WHERE
PREGNANCYCODE = 'Y'
--AND
CV.AvetaID = '010054917'
;
SELECT TOP 100
CV.AvetaID
, CV.MemberID
, CV.FechaEligibilidad
, CV.FechaTerminacion
, CV.[Group]
, CV.[ST_Group]
, CV.PregnancyCode
, CV.LanguageCode
, CV.IndValue
FROM ENTERPRISEINTERFACES.CVS.CVSSQELETONLAYOUT AS CV
WHERE 1 = 1
-- AND IndValue = 'P00310749499'
--PREGNANCYCODE = 'Y'
AND CV.AvetaID = '010054917'--'010585502'
;
SELECT TOP 100
CV.Account
, CV.[Group]
, CV.PregnancyCode
, CV.MemberID
, CV.FechaEligibilidad
, CV.FechaTerminacion
, CV.IndValue
FROM ENTERPRISEINTERFACES.CVS.CVSSQELETONLAYOUT AS CV
WHERE 1 = 1
-- AND IndValue = 'P00310749499'
--PREGNANCYCODE = 'Y'
AND CV.AvetaID = '010054917'
;
SELECT TOP 100 *
FROM ENTERPRISEINTERFACES.CVS.CVSSQELETONLAYOUT AS CV
WHERE 1 = 1
-- AND IndValue = 'P00310749499'
--PREGNANCYCODE = 'Y'
AND CV.AvetaID = '010585502'
;
| true |
bff01138a4200a35a56c4b318d0cabcaf141919c | SQL | whlee21/aumc-daily | /init_load/sprint_2/itf_cost_o_1.sql | UTF-8 | 5,059 | 3.34375 | 3 | [] | no_license | /*****************************************************
프로그램명 : ITF_COST_O_1.SQL
작성자 : Won Jong Bok
수정자 :
최초 작성일 : 2020-12-03
수정일 :
소스 테이블(기본) :
소스 테이블(참조) :
프로그램 설명 : 외래 COST 정보 선적재 1
cnt:
time:
*****************************************************/
DROP TABLE IF EXISTS ITFCDMPV532_daily.ITF_COST_O_1;;
CREATE TABLE ITFCDMPV532_daily.ITF_COST_O_1 AS
SELECT A.PATNO
, A.MEDDATE
, A.ORDTABLE
, A.ORDDATE
, A.ORDSEQNO
, A.ORDCODE
, A.SUGACODE
, (CASE
WHEN A.PATTYP IN ('23', '31', '32', '40')
AND A.TYPECD = 'CA'
AND A.OWNRAT != '100'
AND ( (A.INSTYP IN ('0', '2', '7')
AND A.EXECDATE < '2019-03-01')
OR (A.INSTYP = '8'
AND A.EXECDATE >= '2019-03-01')) THEN
'25'
WHEN S.NOPTVALUE4::INT = 5
AND A.ACTMATYP = '1' THEN
'06'
WHEN S.NOPTVALUE4::INT = 7
AND A.ACTMATYP = '1' THEN
'08'
ELSE
S.NOPTVALUE4::text
END)
NACCUCD
, CASE WHEN A.JOBFG = 'R' THEN '[취소]' ELSE '' END
|| C.KORNAME
|| CASE WHEN A.PJTCODE IS NULL THEN NULL ELSE ' (* 임상연구 *)' END
CODENAME /* 명칭 */
, A.RCPAMT::DECIMAL + A.SPCAMT::DECIMAL + COALESCE (A.YSCHAAMT, 0)::DECIMAL + COALESCE (A.VATAMT, 0)::DECIMAL RCPAMT /* 총액 */
, A.INSTYP INSTYP --진찰료 전액본인부담으로 변경
, COALESCE (A.YSCHAAMT, 0) YSCHAAMT
, A.SPCAMT SPCAMT
, A.TYPECD TYPECD
, A.OWNRAT
, A.PATTYP
, A.RCPTYP
, A.OIFG
, D.INSINTYP
, 0 SELRAT
, A.LARGCD
, A.EXECDATE
, A.PATFG
, a.edittime
, a.meddept
FROM ods_daily.AOOPCALT A
, ods_daily.ACPRICST C
, ods_daily.CSCOMCDT S
, ods_daily.ACPRICST D
, ods_daily.ACPRICST E
WHERE 1=1
--AND A.PATNO = :PATNO
--AND A.RCPDATE = TO_DATE (:RCPDATE, 'YYYY-MM-DD')
--AND A.RCPSEQ = :RCPSEQ
--AND A.APPATFG = :PATFG
and a.rejttime is null
AND COALESCE (A.JOBFG, '*') != 'R'
AND CASE WHEN A.RCPTYP = 'J' THEN A.MEDDATE ELSE -- 31800481
CASE WHEN A.ORDCODE = 'XAU00001' THEN A.MEDDATE
WHEN A.ORDCODE = 'XAU00002' THEN A.MEDDATE
ELSE A.RCPDATE
END
END ::DATE
<= A.RCPDATE::DATE --2015.09.01 KEJ 의료질평가지원금 추가
AND C.SUGACODE = COALESCE(A.SUGACODE, '*')
AND A.EXECDATE BETWEEN C.FROMDATE AND C.TODATE
AND E.SUGACODE = COALESCE (A.ORDCODE, '*')
AND A.MEDDATE BETWEEN E.FROMDATE AND E.TODATE
AND S.LARGECODE = 'AI'
AND S.MIDGCODE = 'AI200'
AND S.SMALLGCODE = E.ACTTYP
AND A.PATTYP || A.TYPECD != '1077' --240237581
--[선별급여항목제외]-----------------------
AND D.SUGACODE = COALESCE ( A.SUGACODE, '*')
AND A.EXECDATE BETWEEN D.FROMDATE AND D.TODATE
AND (
(A.INSTYP || D.INSINTYP NOT IN ('01', '21', '76')
AND A.EXECDATE < '2019-03-01')
OR SUBSTR (A.PATTYP, 1, 1) NOT IN ('2', '3', '4')
OR A.TYPECD IN ('ST', '99')
OR COALESCE (D.SELRAT, 0) = 0
OR A.LARGCD NOT IN ('AA', 'BB', 'DD', 'EE')
)
AND A.recdtyp != 'G'
;;
-----------------------------check cnt
insert into ods_daily.etl_task_check(task_grp_id, task_id, table_name, cnt)
select (SELECT last_value FROM etl_task_check_grp_id), 'itf_cost_o_1' , 'itf_cost_o_1', count(*) as cnt
from itfcdmpv532_daily.itf_cost_o_1 ; | true |
4b74706d75404542b3d0a710fe5a3ec88c1426fd | SQL | nguyensjsu/su18-202-got | /renato/database_script.sql | UTF-8 | 1,805 | 3.359375 | 3 | [] | no_license |
-- ---
-- Globals
-- ---
-- SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
-- SET FOREIGN_KEY_CHECKS=0;
-- ---
-- Table 'users'
--
-- ---
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`name` VARCHAR(300) NULL DEFAULT NULL,
`email` VARCHAR(100) NULL DEFAULT NULL,
`facebook_id` VARCHAR(100) NULL DEFAULT NULL,
`password_hash` VARCHAR NULL DEFAULT NULL,
`token` VARCHAR NULL DEFAULT NULL,
`token_expire_at` INTEGER NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'push_tokens'
--
-- ---
DROP TABLE IF EXISTS `push_tokens`;
CREATE TABLE `push_tokens` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`user_id` INTEGER NULL DEFAULT NULL,
`device_token` VARCHAR NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'rewards'
--
-- ---
DROP TABLE IF EXISTS `rewards`;
CREATE TABLE `rewards` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`user_id` VARCHAR NULL DEFAULT NULL,
`balance` INTEGER NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Foreign Keys
-- ---
ALTER TABLE `push_tokens` ADD FOREIGN KEY (id) REFERENCES `users` (`id`);
ALTER TABLE `rewards` ADD FOREIGN KEY (user_id) REFERENCES `users` (`id`);
-- ---
-- Table Properties
-- ---
-- ALTER TABLE `users` ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ALTER TABLE `push_tokens` ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ALTER TABLE `rewards` ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ---
-- Test Data
-- ---
-- INSERT INTO `users` (`id`,`name`,`email`,`facebook_id`,`password_hash`,`token`,`token_expire_at`) VALUES
-- ('','','','','','','');
-- INSERT INTO `push_tokens` (`id`,`user_id`,`device_token`) VALUES
-- ('','','');
-- INSERT INTO `rewards` (`id`,`user_id`,`balance`) VALUES
-- ('','','');
| true |
11cd8c9c9d390793d386382cccd531c648cc7909 | SQL | sofiaromorales/db-delivery | /simulaciones/secundarias/3_asignacion_usuarios.sql | UTF-8 | 3,628 | 4 | 4 | [] | no_license | ---SIMULACION ASIGNACION DE USUARIOS
CREATE OR REPLACE PROCEDURE asignacion_usuarios( today DATE )
IS
id_usuario INTEGER;
id_proveedor INTEGER;
flag_registro INTEGER;
usuario_nombre VARCHAR(30);
usuario_apellido VARCHAR(30);
nombre_proveedor VARCHAR(30);
BEGIN
DBMS_OUTPUT.PUT_LINE('3. ------SIMULACIÓN ASIGNACIÓN DE USUARIO-------');
DBMS_OUTPUT.PUT_LINE('3.1 Buscando usuarios que no tnegan registros con alguna empresa proveedora...');
/* 1. Se selecciona el id del usuario y el id del proveedor que no tienen un registro */
SELECT u.cedula, p.id, p.datos_empresa.nombre
INTO id_usuario, id_proveedor, nombre_proveedor
FROM usuarios u
CROSS JOIN proveedores p
WHERE NOT EXISTS (
SELECT *
FROM registros r
WHERE r.id_proveedor = p.id AND r.id_usuario = u.cedula
)
FETCH FIRST 1 ROWS ONLY
;
SELECT u.primer_nombre, u.primer_apellido
INTO usuario_nombre, usuario_apellido
FROM usuarios u
WHERE u.cedula = id_usuario
;
DBMS_OUTPUT.PUT_LINE('3.2 El usuario '||usuario_nombre||' '||usuario_apellido||' no esta registrado en el app de delivery '||nombre_proveedor);
DBMS_OUTPUT.PUT_LINE('3.3 Se procede a registrar el usuario en esta aplicación...');
/* 2. Se crea el registro */
INSERT INTO registros values (id_usuario,id_proveedor,today);
/* 3.Verificar si todos los usuarios estan registrados*/
SELECT COUNT(u.cedula)
INTO flag_registro
FROM usuarios u
WHERE NOT EXISTS (
SELECT r.id_usuario
FROM registros r
WHERE r.id_usuario = u.cedula
);
DBMS_OUTPUT.PUT_LINE('3.4 Verificando que todos los usuarios esten registrados en una aplicación de delivery...');
IF flag_registro = 0 THEN
DBMS_OUTPUT.PUT_LINE('3.5 Todas los usarios han sido registrados');
ELSE
DBMS_OUTPUT.PUT_LINE('3.5 Existen usuarios sin registro');
END IF;
WHILE flag_registro <> 0
LOOP
/* 3. Se selecciona el id del usuario que no tenga registro */
SELECT u.cedula, u.primer_nombre, u.primer_apellido
INTO id_usuario, usuario_nombre, usuario_apellido
FROM usuarios u
WHERE NOT EXISTS (
SELECT r.id_usuario
FROM registros r
WHERE r.id_usuario = u.cedula
)
FETCH FIRST 1 ROWS ONLY
;
DBMS_OUTPUT.PUT_LINE('3.6 El usuario '||usuario_nombre||' '||usuario_apellido||' no esta registrado en el ningun app de delivery');
/* 4. Se selecciona random id del proveedor random */
SELECT p.id, p.datos_empresa.nombre
INTO id_proveedor, nombre_proveedor
FROM proveedores p
ORDER BY DBMS_RANDOM.RANDOM
FETCH FIRST 1 ROWS ONLY
;
DBMS_OUTPUT.PUT_LINE('3.7 Se registra el usuario en la app de delivery'|| nombre_proveedor);
/* 5. Se crea el registro */
INSERT INTO registros values (id_usuario,id_proveedor,today);
/* 6.Verificar si todos los usuarios estan registrados*/
SELECT COUNT(u.cedula)
INTO flag_registro
FROM usuarios u
WHERE NOT EXISTS (
SELECT r.id_usuario
FROM registros r
WHERE r.id_usuario = u.cedula
);
DBMS_OUTPUT.PUT_LINE('3.8 Verificando que todos los usuarios esten registrados en una aplicación de delivery...');
IF flag_registro = 0 THEN
DBMS_OUTPUT.PUT_LINE('3.9 Todas los usarios han sido registrados');
ELSE
DBMS_OUTPUT.PUT_LINE('3.9 Existen usuarios sin registro');
END IF;
END LOOP;
END;
| true |
39ee676b465f84f39d4c41e98364dd0eb9e079d9 | SQL | gabrielareisg/replicado | /resources/queries/Graduacao.obterIntercambioPorCodpes.sql | UTF-8 | 365 | 2.9375 | 3 | [] | no_license | SELECT O.nomorgpnt, P.nompas, I.dtainiitb, I.dtafimitb from INTERCAMBIOUSPORGAO I
INNER JOIN LOCALIZAPESSOA L ON I.codpes = L.codpes
INNER JOIN ORGAOPRETENDENTE O ON I.codorg = O.codorg
INNER JOIN PAIS P ON O.codpas = P.codpas
WHERE L.tipvin = 'ALUNOGR'
AND I.dtafimitb > GETDATE()
AND L.codundclg IN (__codundclgi__)
AND I.codpes = convert(int,:codpes) | true |
04a3ecde5f6de7c931f1ff5fb7d2eda2091f8717 | SQL | polyglotm/coding-dojo | /coding-challange/codewars/7kyu/2020-09-10~2020-10-06/easy-sql-ascii-converter/easy-sql-ascii-converter.sql | UTF-8 | 257 | 2.734375 | 3 | [] | no_license | -- easy-sql-ascii-converter
-- Easy SQL: ASCII Converter
-- difficulty: 7kyu
-- https://www.codewars.com/kata/594804a218e96caa8d00051b/
SELECT id,
ascii(left(name, 1)) AS name,
birthday,
ascii(left(race, 1)) AS race
FROM demographics;
| true |
1207c0493f0fe80a9741ad75c8bbb05f13a364bb | SQL | afubuntu/PersonalProjects | /ctennisdb/tables/data/non_dependent/data_ctennistournaments.sql | UTF-8 | 3,322 | 3.78125 | 4 | [] | no_license | DO
$do$
declare __table_name character varying(100);
__rows_count numeric;
begin
__table_name := 'ctennistournaments';
if exists (select 1 from information_schema.tables where table_schema='public' and table_name=__table_name and table_type='BASE TABLE') then
insert into ctennistournaments
(
ctname,
ctcategory,
ctcountry,
ctsurface,
ctlabel,
ctcreatedon
)
select
tmp.ctname,
tmp.ctcategory,
tmp.ctcountry,
tmp.ctsurface,
tmp.ctlabel,
current_timestamp
from
( select 'Sydney International' as ctname, (select ctdid from ctennistournamentscategories where ctcode='atp250') as ctcategory, 'AUS' as ctcountry, (select ctcode from ctennissurfaces where lower(ctlabel)=lower('Outdoor Hard')) as ctsurface, 'Sydney' as ctlabel
union all select 'Hopman Cup' as ctname, (select ctdid from ctennistournamentscategories where ctcode='itf') as ctcategory, 'AUS' as ctcountry, (select ctcode from ctennissurfaces where lower(ctlabel)=lower('Hard')) as ctsurface, 'Perth' as ctlabel
union all select 'Indian Wells Challenger' as ctname, (select ctdid from ctennistournamentscategories where ctcode='atpchallenger') as ctcategory, 'USA' as ctcountry, (select ctcode from ctennissurfaces where lower(ctlabel)=lower('Hard')) as ctsurface, 'Indian Wells Challenger' as ctlabel
union all select 'Phoenix Challenger' as ctname, (select ctdid from ctennistournamentscategories where ctcode='atpchallenger') as ctcategory, 'USA' as ctcountry, (select ctcode from ctennissurfaces where lower(ctlabel)=lower('Hard')) as ctsurface, 'Phoenix Challenger' as ctlabel
union all select 'Brisbane International' as ctname, (select ctdid from ctennistournamentscategories where ctcode='atp250') as ctcategory, 'AUS' as ctcountry, (select ctcode from ctennissurfaces where lower(ctlabel)=lower('Outdoor Hard')) as ctsurface, 'Brisbane' as ctlabel
union all select 'Brasil Open - Sao Paulo' as ctname, (select ctdid from ctennistournamentscategories where ctcode='atp250') as ctcategory, 'BRA' as ctcountry, (select ctcode from ctennissurfaces where lower(ctlabel)=lower('Indoor Clay')) as ctsurface, 'Sao Paulo' as ctlabel
union all select 'TEB BNP Paribas Istanbul Open - Istanbul' as ctname, (select ctdid from ctennistournamentscategories where ctcode='atp250') as ctcategory, 'TUR' as ctcountry, (select ctcode from ctennissurfaces where lower(ctlabel)=lower('Clay')) as ctsurface, 'Istanbul' as ctlabel
union all select 'Mubadala World Tennis Championship' as ctname, (select ctdid from ctennistournamentscategories where ctcode='lvr') as ctcategory, 'ZZZ' as ctcountry, (select ctcode from ctennissurfaces where lower(ctlabel)=lower('Hard')) as ctsurface, 'Mubadala World Tennis Championship' as ctlabel
) as tmp
left outer join ctennistournaments as t
on lower(t.ctname)=lower(tmp.ctname)
where t.ctname is null;
GET DIAGNOSTICS __rows_count=ROW_COUNT;
raise notice '<%> row(s) has(ve) been successfully inserted.',__rows_count;
else
raise notice 'The table <%> does not exist. It should be created first before inserting records into it.',__table_name;
end if;
end
$do$; | true |
99e0491c3d3320735b38c6632750f003143c9052 | SQL | Wardenclock1759/kursovaya | /migrations/20200912004236_project.up.sql | UTF-8 | 215 | 2.640625 | 3 | [] | no_license | CREATE TABLE "project" (
api_key varchar NOT NULL,
project_id bigserial NOT NULL,
created_at time NOT NULL,
updated_at time,
is_active boolean,
primary key (api_key, project_id, is_active)
); | true |
b90cbe09ebfd8b1adcc3a543b5906612865b6632 | SQL | diegopajarito/CyclingPathAnalysis | /sql/frictions_description.sql | UTF-8 | 6,113 | 4.21875 | 4 | [] | no_license |
-- Data Management for describing frictions
-- We start from the dissolved grid spots with proportion of
-- walking / cycling segments between 50% and 150%
----------------------------------------------------------
--- Second Attempt
----------------------------------------------------------
-- Spatial aggregation of the places possibly having frictions
-- A) the grid spots filling the different conditions
drop materialized view grid.level3_places;
create materialized view grid.level3_places as
select *, round((n_segments_l_5kmh * 100.0 / n_cycling_segments),2) intensity
from grid.grid_reduced
where n_segments_l_5kmh > 2 and
n_cycling_segments > 2 and
(n_segments_l_5kmh * 100.0 / n_cycling_segments) > 50.0 and
(n_segments_l_5kmh * 100.0 / n_cycling_segments) < 200.0 and
st_intersects(geometry, (select st_union(st_buffer(geometry, 0.00025))
from trips.od)) = FALSE;
CREATE INDEX sidx_level3_places ON grid.level3_places USING gist (geometry);
-- B) the aggregated spots
drop materialized view grid.level3_places_agg;
create materialized view grid.level3_places_agg as
select (st_dump(st_union(geometry))).path[1] id, (st_dump(st_union(geometry))).geom geometry
from grid.level3_places;
CREATE INDEX sidx_level3_places_agg ON grid.level3_places_agg USING gist (geometry);
-- C) Summary statistics of aggregated spots or frictions!!
drop materialized view grid.frictions_level3;
create materialized view grid.frictions_level3 as
select a.id, count(g.*) n_grid_spots,
round(avg(g.n_segments_l_5kmh),0) n_segments_l_5kmh,
round(avg(g.n_cycling_segments),0) n_cycling_segments,
round(avg(g.intensity),2) intensity,
round(avg(g.n_trips),0) n_trips,
round(avg(g.n_segments),0) n_segments,
max(g.city) city,
max(in_umz) in_umz,
a.geometry geometry
from grid.level3_places_agg a, grid.level3_places g
where ST_Contains(a.geometry, g.geometry)
group by a.id, a.geometry
order by count(g.*);
CREATE INDEX sidx_frictions_level3 ON grid.frictions_level3 USING gist (geometry);
----------------------------------------------------------
--- Firt Attempt
----------------------------------------------------------
drop table grid.frictions;
select * from grid.frictions;
-- 1) Update UMZ and FUA
update grid.frictions f
set in_fua = 1
from aoi.fua u
where st_intersects(f.geometry,u.geometry);
update grid.frictions f
set in_umz = 1
from aoi.umz u
where st_intersects(f.geometry,u.geometry);
-- 2) Update trips count
update grid.frictions f
set has_trips = 1
from trips.trips_raw t
where st_intersects(f.geometry,t.geometry);
update grid.frictions f
set n_trips = (select count(*)
from trips.trips_raw ti
where st_intersects(ti.geometry, f.geometry))
from trips.trips_raw t
where st_intersects(f.geometry, t.geometry);
-- 3) Update segments count
update grid.frictions f
set n_segments = (select count(*)
from trips.segments si
where st_intersects(si.geometry, f.geometry))
from trips.segments s
where st_intersects(f.geometry, s.geometry);
-- < 5 km/h
update grid.frictions f
set n_segments_l_5kmh = (select count(*)
from trips.segments si
where si.speed_geometry < 5 and
st_intersects(si.geometry, f.geometry))
from trips.segments s
where s.speed_geometry < 5 and
st_intersects(f.geometry, s.geometry);
-- 5 - 10 km/h
update grid.frictions f
set n_segments_b_5_10kmh = (select count(*)
from trips.segments si
where si.speed_geometry between 5 and 10 and
st_intersects(si.geometry, f.geometry))
from trips.segments s
where s.speed_geometry between 5 and 10 and
st_intersects(f.geometry, s.geometry);
-- 10 - 20 km/h
update grid.frictions f
set n_segments_b_10_20kmh = (select count(*)
from trips.segments si
where si.speed_geometry between 10 and 20 and
st_intersects(si.geometry, f.geometry))
from trips.segments s
where s.speed_geometry between 10 and 20 and
st_intersects(f.geometry, s.geometry);
-- 20 - 30 km/h
update grid.frictions f
set n_segments_b_20_30kmh = (select count(*)
from trips.segments si
where si.speed_geometry between 20 and 30 and
st_intersects(si.geometry, f.geometry))
from trips.segments s
where s.speed_geometry between 20 and 30 and
st_intersects(f.geometry, s.geometry);
-- 30 - 50 km/h
update grid.frictions f
set n_segments_b_30_50kmh = (select count(*)
from trips.segments si
where si.speed_geometry between 30 and 50 and
st_intersects(si.geometry, f.geometry))
from trips.segments s
where s.speed_geometry between 30 and 50 and
st_intersects(f.geometry, s.geometry);
-- 50 - 70 km/h
update grid.frictions f
set n_segments_b_50_70kmh = (select count(*)
from trips.segments si
where si.speed_geometry between 50 and 70 and
st_intersects(si.geometry, f.geometry))
from trips.segments s
where s.speed_geometry between 50 and 70 and
st_intersects(f.geometry, s.geometry);
-- > 70 km/h
update grid.frictions f
set n_segments_h_70kmh = (select count(*)
from trips.segments si
where si.speed_geometry > 70 and
st_intersects(si.geometry, f.geometry))
from trips.segments s
where s.speed_geometry > 70 and
st_intersects(f.geometry, s.geometry);
-- Updatint cycling segments
update grid.frictions
set n_cycling_segments = n_segments_b_5_10kmh + n_segments_b_10_20kmh + n_segments_b_20_30kmh + n_segments_b_30_50kmh;
-- count trips origin and destination
update grid.frictions f
set n_origin = (select count(*)
from trips.od od
where od.type = 'origin' and
st_intersects(od.geometry, f.geometry))
from trips.od o
where o.type = 'origin' and
st_intersects(f.geometry, o.geometry);
update grid.frictions f
set n_destination = (select count(*)
from trips.od od
where od.type = 'destination' and
st_intersects(od.geometry, f.geometry))
from trips.od o
where o.type = 'destination' and
st_intersects(f.geometry, o.geometry);
-- Create a view with the relevant frictions
create or replace view grid.relevant_frictions as
select fid, in_umz, in_fua, n_segments, n_trips, n_segments_l_5kmh, n_cycling_segments, city, area, geometry
from grid.frictions; | true |
fefcce739f72785db364ea7411ce4f653d6d000f | SQL | hugo098/Curso-PL-SQL | /triggerCompound.sql | UTF-8 | 838 | 2.96875 | 3 | [] | no_license | CREATE OR REPLACE TRIGGER trigger1 FOR
DELETE OR INSERT OR UPDATE ON regions
COMPOUND TRIGGER
BEFORE STATEMENT IS BEGIN
INSERT INTO log_table VALUES (
'BEFORE STATEMENT', user
);
END BEFORE STATEMENT;
AFTER STATEMENT IS BEGIN
INSERT INTO log_table VALUES (
'AFTER STATEMENT', user
);
END AFTER STATEMENT;
BEFORE EACH ROW IS BEGIN
INSERT INTO log_table VALUES (
'BEFORE EACH ROW', user
);
END BEFORE EACH ROW;
AFTER EACH ROW IS BEGIN
INSERT INTO log_table VALUES (
'AFTER EACH ROW', user
);
END AFTER EACH ROW;
END trigger1;
/
ALTER TRIGGER TR1_REGION DISABLE;
INSERT INTO REGIONS VALUES(9001,'REGION9001');
UPDATE REGIONS SET REGION_NAME='AAA';
COMMIT; | true |
e67874b574e9b482052dfd600ac7747c93428956 | SQL | eragonwien/TTWeb | /TTWebMVC/SQL/04-view-v_appuser.sql | UTF-8 | 477 | 3.1875 | 3 | [
"MIT"
] | permissive | CREATE OR REPLACE VIEW v_appuser AS
SELECT
appuser.id AS appuser_id,
appuser.email AS email,
appuser.title AS title,
appuser.firstname AS firstname,
appuser.lastname AS lastname,
appuser.disabled AS disabled,
appuser.active AS active,
role.id AS role_id,
role.name AS role_name,
role.description AS role_description
FROM
appuser
LEFT JOIN role on appuser.role_id=role.id;
| true |
83d9531c23c8949f56be51f2f1fd957e47b9e46e | SQL | Juanddiazm/proyectoBasesDeDatos | /Script Nivel 3/pkRegistroNivel3.sql | UTF-8 | 1,401 | 2.953125 | 3 | [] | no_license | CREATE OR REPLACE PACKAGE pkClienteNivel3 IS
FUNCTION pRegistrarCliente(ivCedula VARCHAR2, ivNombre VARCHAR2, ivFechaNacimiento VARCHAR2, ivDireccion VARCHAR, ivTelefono VARCHAR2)RETURN VARCHAR2;
FUNCTION pRegistrarAnomalia(ivNombre IN VARCHAR2, ivId IN VARCHAR2) RETURN VARCHAR2;
FUNCTION pRegistrarProducto(ivIdProducto IN VARCHAR2, ivNombre IN VARCHAR2, ivTipo_prod_id IN VARCHAR2)RETURN VARCHAR2;
end pkClienteNivel3;
CREATE OR REPLACE PACKAGE BODY pkClienteNivel3 IS
FUNCTION pRegistrarCliente(ivCedula VARCHAR2, ivNombre VARCHAR2, ivFechaNacimiento VARCHAR2, ivDireccion VARCHAR, ivTelefono VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
pkRegistroNivel2.pRegistrarCliente(ivCedula , ivNombre , ivFechaNacimiento , ivDireccion , ivTelefono);
RETURN 'No_Exception';
EXCEPTION
WHEN OTHERS THEN
RETURN SQLERRM;
END pRegistrarCliente;
FUNCTION pRegistrarAnomalia(ivNombre IN VARCHAR2, ivId IN VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
pkRegistroNivel2.pResgistrarAnomalia(vNombre , ivId);
RETURN'No_Exception';
EXCEPTION
WHEN OTHERS THEN
RETURN SQLERRM;
END pRegistrarAnomalia;
FUNCTION pRegistrarProducto(ivIdProducto IN VARCHAR2, ivNombre IN VARCHAR2, ivTipo_prod_id IN VARCHAR2)
return varchar2
is
begin
pkRegistroNivel2.pRegistrarProducti(ivIdProducto , ivNombre , ivTipo_prod_id );
RETURN'No_Exception';
EXCEPTION
WHEN OTHERS THEN
RETURN SQLERRM;
end pRegistrarProducto;
end pkClienteNivel3; | true |
8465026771fc27d63dc4709a5c4a11ef9ea1977f | SQL | longniao/torstack | /examples/example.sql | UTF-8 | 832 | 3.015625 | 3 | [
"MIT"
] | permissive | CREATE database test;
GRANT ALL privileges ON test.* to test@'127.0.0.1' identified by 'test';
use test;
CREATE TABLE `user_account` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL DEFAULT '',
`nickname` char(36) NOT NULL DEFAULT '',
`password` char(64) NOT NULL DEFAULT '',
`salt` char(10) NOT NULL DEFAULT '',
`must_change_password` tinyint(2) unsigned NOT NULL DEFAULT '0',
`banned` tinyint(2) unsigned NOT NULL DEFAULT '0',
`suspended` tinyint(2) unsigned NOT NULL DEFAULT '0',
`status` tinyint(2) unsigned NOT NULL DEFAULT '0',
`created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_name` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
| true |
eb413e62ccb0feed03472382485cf93ce8ed1d08 | SQL | muddasani/poliana_schema | /prod/entities_external.sql | UTF-8 | 3,651 | 2.890625 | 3 | [] | no_license | CREATE DATABASE entities_external;
CREATE EXTERNAL TABLE IF NOT EXISTS entities_external.candidate_ids(
recipient_ext_id STRING,
crp_name STRING,
party STRING,
dist_id_run_for STRING,
fec_cand_id STRING
)
ROW FORMAT SERDE 'com.bizo.hive.serde.csv.CSVSerde'
LOCATION 's3n://poliana.prod/entities/candidate_contribution_ids/';
CREATE EXTERNAL TABLE IF NOT EXISTS entities_external.congressional_committee_ids(
code STRING,
cmte_name STRING
)
row format serde 'com.bizo.hive.serde.csv.CSVSerde'
LOCATION 's3n://poliana.prod/entities/congressional_committee_ids/';
--SCHEMA BROKEN!!! TODO
CREATE EXTERNAL TABLE IF NOT EXISTS entities_external.current_committee_membership_json(
committee MAP<
STRING,
STRING
>
)
ROW FORMAT SERDE 'com.proofpoint.hive.serde.JsonSerde'
WITH SERDEPROPERTIES ('errors.ignore' = 'true')
LOCATION 's3n://poliana.prod/entities/current_committee_members/';
CREATE EXTERNAL TABLE IF NOT EXISTS entities_external.current_committees_nested(
rss_url STRING,
name STRING,
url STRING,
house_committee_id STRING,
phone STRING,
subcommittees ARRAY<STRUCT<
phone: STRING,
thomas_id: STRING,
name: STRING,
address: STRING
>>,
address STRING,
type STRING,
thomas_id STRING
)
ROW FORMAT SERDE 'com.proofpoint.hive.serde.JsonSerde'
WITH SERDEPROPERTIES ('errors.ignore' = 'true')
LOCATION 's3n://poliana.prod/entities/current_committees/';
CREATE EXTERNAL TABLE IF NOT EXISTS entities_external.legislators(
first_name STRING,
last_name STRING,
official_full STRING,
party STRING,
thomas_id STRING,
bioguide_id STRING,
opensecrets_id STRING,
fec_id STRING,
votesmart_id STRING,
ballotpedia STRING,
lis_id STRING,
wikipedia_id STRING,
govtrack_id STRING,
maplight_id STRING,
icpsr_id STRING,
cspan_id STRING,
house_history_id STRING,
washington_post_id STRING,
gender STRING,
birthday INT,
religion STRING
)
LOCATION 's3n://poliana.prod/entities/legislators_flat/';
CREATE EXTERNAL TABLE IF NOT EXISTS entities_external.legislators_flat_terms (
first_name STRING,
last_name STRING,
official_full STRING,
party STRING,
thomas_id STRING,
bioguide_id STRING,
opensecrets_id STRING,
fec_id STRING,
votesmart_id STRING,
ballotpedia STRING,
lis_id STRING,
wikipedia_id STRING,
govtrack_id STRING,
maplight_id STRING,
icpsr_id STRING,
cspan_id STRING,
house_history_id STRING,
washington_post_id STRING,
gender STRING,
birthday STRING,
religion STRING,
term_start STRING,
term_end STRING,
beginTimestamp INT,
endTimestamp INT,
term_state STRING,
term_type STRING,
district STRING,
term_state_rank STRING
)
LOCATION 's3n://poliana.prod/entities/legislators_flat_terms/';
CREATE EXTERNAL TABLE IF NOT EXISTS entities_external.senate_terms LIKE entities_external.legislators_flat_terms
LOCATION 's3n://poliana.prod/entities/senate_terms/';
CREATE EXTERNAL TABLE IF NOT EXISTS entities_external.house_terms LIKE entities_external.legislators_flat_terms
LOCATION 's3n://poliana.prod/entities/house_terms/';
CREATE EXTERNAL TABLE entities_external.recip_id_to_bioguide_ids (
bioguide_id STRING,
recipient_ext_id STRING,
chamber STRING,
state_name STRING,
first_name STRING,
last_name STRING,
party STRING,
in_office STRING,
website STRING,
contact_form STRING
)
ROW FORMAT SERDE 'com.bizo.hive.serde.csv.CSVSerde'
LOCATION 's3n://poliana.prod/entities/recip_ids_to_bioguide/'; | true |
635c03c2d1b5f73e243e5c7d792c8682aee5405f | SQL | j7ng/CLFY_SA | /SA/Tables/X_BI_SCENARIOS.sql | UTF-8 | 809 | 3.25 | 3 | [] | no_license | CREATE TABLE sa.x_bi_scenarios (
objid NUMBER(22) NOT NULL,
x_service_plan_type VARCHAR2(50 BYTE),
insert_timestamp DATE DEFAULT SYSDATE NOT NULL,
update_timestamp DATE DEFAULT SYSDATE NOT NULL,
CONSTRAINT tf_x_bi_scenarios_pk PRIMARY KEY (objid)
);
COMMENT ON TABLE sa.x_bi_scenarios IS 'Source for the BI with the flow id details';
COMMENT ON COLUMN sa.x_bi_scenarios.objid IS 'Stores the unique identifier for each record';
COMMENT ON COLUMN sa.x_bi_scenarios.x_service_plan_type IS 'Gives the details like which service plan user is holding like limited, unlimited or all you need';
COMMENT ON COLUMN sa.x_bi_scenarios.insert_timestamp IS 'Time and date when the row was entered.';
COMMENT ON COLUMN sa.x_bi_scenarios.update_timestamp IS 'Last date when the record was last modified'; | true |
cc9b45056ae94f65f871c1d24ec3f8992b52e649 | SQL | aldianfebriyanto/project_magang | /schedule/database_crud.sql | UTF-8 | 6,457 | 2.75 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 29, 2018 at 06:28 AM
-- Server version: 10.1.26-MariaDB
-- PHP Version: 7.1.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: `crud`
--
CREATE DATABASE IF NOT EXISTS `crud` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `crud`;
-- --------------------------------------------------------
--
-- Table structure for table `jobs`
--
DROP TABLE IF EXISTS `jobs`;
CREATE TABLE `jobs` (
`id_job` int(11) NOT NULL,
`nomor` varchar(55) NOT NULL,
`tanggal` date NOT NULL,
`store` varchar(100) NOT NULL,
`alamat` varchar(250) NOT NULL,
`kategori` varchar(55) NOT NULL,
`keterangan` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `jobs`
--
INSERT INTO `jobs` (`id_job`, `nomor`, `tanggal`, `store`, `alamat`, `kategori`, `keterangan`) VALUES
(7, '12345 ', '2018-04-10', 'store 2', 'jl.gandaria', 'Standby', 'Sudah'),
(9, '1008', '2018-03-31', 'store 3', 'bulungan1', 'Maintenance', 'Belum'),
(10, '2552', '2018-02-26', 'store 1', 'Jl. Cipete raya', 'Maintenance', 'Sudah'),
(13, '1080ti', '2055-05-05', 'store 4', 'Jl. Bahari', 'Standby', '555'),
(14, '132535', '6662-05-05', 'store 4', 'jl. cinere raya', 'Maintenance', 'off'),
(17, '4555', '2055-05-05', 'store 5', 'jl limo 5', 'Standby', 'ready'),
(18, '1245', '2018-02-01', 'store 2', 'jl.pondok labu', 'Standby', 'System Error'),
(19, '12352', '2017-02-11', 'store 2', 'jl.kamboja', 'Standby', 'System Error'),
(20, '2135', '2017-11-02', 'store 2', 'Jl. Melati', 'Standby', 'System Error'),
(21, '2343', '2109-04-02', 'store 2', 'jl.kemang raya', 'Maintenance', 'Sudah'),
(22, '1354', '2019-04-12', 'store 2', 'Jl. Karang Raya', 'Standby', 'System Error'),
(24, '12342', '2017-12-02', 'store 3', 'Jl.karang raya', 'Maintenance', 'System Error'),
(25, '123231', '2018-03-22', 'Jl.Bunguran No. 35 B', 'Jl.Bunguran No. 35 B', 'Maintenance', 'asd'),
(26, '324432', '2018-03-22', 'Jl.Raya Wonokromo', 'Jl.Raya Wonokromo', 'Maintenance', 'sad'),
(27, '432', '2018-03-23', 'JL.Bubutan No. 1-7', 'JL.Bubutan No. 1-7', 'Maintenance', 'SDdsdsa'),
(28, 'q34q4', '2018-03-15', 'JL. AHMAD YANI', 'JL. AHMAD YANI', 'Maintenance', 'zdzfdas'),
(29, '213321', '2018-03-06', 'JL.Bubutan No. 1-7', 'JL.Bubutan No. 1-7', 'Maintenance', 'dsfdsf'),
(30, '3443221', '2018-03-23', 'JL. Veteran No. 2', 'JL. Veteran No. 2', 'Maintenance', 'gfd'),
(31, '54321', '2018-03-19', 'Jl. Hayam Wuruk G34 - G45', 'Jl. Hayam Wuruk G34 - G45', 'Maintenance', 'fdsdfs'),
(32, '67786', '2018-10-26', 'MULYOSARI SURABAYA', 'MULYOSARI SURABAYA', 'Maintenance', ''),
(33, '242', '2018-03-08', 'JL. AHMAD YANI', 'JL. AHMAD YANI', 'Maintenance', ''),
(34, '121212', '2018-03-14', '1027', 'Jl.Raya Wonokromo', 'Maintenance', ''),
(35, '7778', '2018-03-07', '1032', 'Jl.Ahmad Yani 16-18', 'Maintenance', ''),
(36, '54512', '2018-05-25', '1026', 'Jl. Puncak Indah Lontar No. 2', 'Maintenance', ''),
(37, '2132', '2018-03-29', '1038', 'JL. AHMAD YANI', 'Maintenance', ''),
(38, '21231', '2005-05-05', 'ADITYAWARMAN SURABAYA', 'Jl. Hayam Wuruk G34 - G45', 'Maintenance', '');
-- --------------------------------------------------------
--
-- Table structure for table `plus_key`
--
DROP TABLE IF EXISTS `plus_key`;
CREATE TABLE `plus_key` (
`username` varchar(50) NOT NULL,
`pkey` varchar(32) NOT NULL,
`time` varchar(10) NOT NULL,
`status` varchar(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `plus_key`
--
INSERT INTO `plus_key` (`username`, `pkey`, `time`, `status`) VALUES
('1001', '0b5a34676b137197924cdca8507a17cc', '1521443221', 'pending');
-- --------------------------------------------------------
--
-- Table structure for table `plus_login`
--
DROP TABLE IF EXISTS `plus_login`;
CREATE TABLE `plus_login` (
`id` varchar(50) NOT NULL DEFAULT '',
`username` varchar(50) NOT NULL DEFAULT '',
`ip` varchar(20) NOT NULL DEFAULT '',
`tm` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`status` char(3) NOT NULL DEFAULT 'ON'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `plus_signup`
--
DROP TABLE IF EXISTS `plus_signup`;
CREATE TABLE `plus_signup` (
`mem_id` int(3) NOT NULL,
`username` varchar(50) NOT NULL DEFAULT '',
`password` varchar(255) NOT NULL DEFAULT '',
`email` varchar(50) NOT NULL DEFAULT '',
`nama` varchar(160) NOT NULL DEFAULT '',
`division` varchar(50) NOT NULL DEFAULT '',
`phone` varchar(25) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `plus_signup`
--
INSERT INTO `plus_signup` (`mem_id`, `username`, `password`, `email`, `nama`, `division`, `phone`) VALUES
(3, 'kuanh', '6531401f9a6807306651b87e44c05751', 'kuanh@gmail.com', 'juahg', 'IT Support', '0'),
(4, 'lugor', 'a75d6a841eafd550b0a27293ee054614', 'juan@gmail.com', 'Juan Tharo', 'IT Support', '085697604336'),
(5, 'aldianfbrn', '202cb962ac59075b964b07152d234b70', 'aldi@gmail.com', 'aldiansyah', 'IT Support', '353231453532'),
(6, 'aldianfbrnt', '4297f44b13955235245b2497399d7a93', 'aldi270201@gmail.com', 'aldian', 'IT Support', '012312'),
(7, 'aldianfbrnasd', 'a8f5f167f44f4964e6c998dee827110c', 'kjads@asd.com', 'asdsad', 'IT Support', '1263'),
(8, 'farizak', 'd8578edf8458ce06fbc5bb76a58c5ca4', 'fariz17k@gantng.com', 'Fariz', 'IT Solution', '0215632589452');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `jobs`
--
ALTER TABLE `jobs`
ADD PRIMARY KEY (`id_job`),
ADD UNIQUE KEY `nomor` (`nomor`);
--
-- Indexes for table `plus_signup`
--
ALTER TABLE `plus_signup`
ADD PRIMARY KEY (`username`),
ADD UNIQUE KEY `email` (`email`),
ADD UNIQUE KEY `userid` (`username`),
ADD UNIQUE KEY `mem_id` (`mem_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `jobs`
--
ALTER TABLE `jobs`
MODIFY `id_job` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=40;
--
-- AUTO_INCREMENT for table `plus_signup`
--
ALTER TABLE `plus_signup`
MODIFY `mem_id` int(3) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
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 |
b2d95730a0cf12ebad7e276781df8d55e5dd405a | SQL | charlotte-schroder/advanced-postgres | /src/locks_advanced/ex1_monitoring_locks.1.sql | UTF-8 | 738 | 3.390625 | 3 | [] | no_license | /* -----------------------------------------------------------------------------
|
| * Uncomment the line with SELECT pg_sleep(1), and save this file so the
| queries are run. Look at the output from this transaction.
|
| You should see a table displaying data about current locks.
|
| * Follow the instructions in ex1_monitoring_locks.2.sql.
|
*/ -----------------------------------------------------------------------------
-- SELECT pg_sleep(1); -- Give the other transaction time to acquire some locks
SELECT pg_locks.pid,
pg_locks.locktype,
pg_locks.mode,
pg_locks.objid,
pg_locks.granted,
pg_class.relname
FROM pg_locks
LEFT JOIN pg_class
ON pg_locks.relation = pg_class.oid;
| true |
4256435c2bef1793f6a61baa087935d49d969534 | SQL | dickanirwansyah/java-springboot-integrated-javascript | /spring-postgresql/src/main/resources/sql/schema.sql | UTF-8 | 709 | 3.453125 | 3 | [] | no_license | create table category(
id varchar(255) not null unique,
name varchar(255) not null,
disabled boolean not null,
constraint pk_category_id PRIMARY KEY (id)
);
create table book(
idbuku varchar(255) not null unique,
title varchar(255) not null,
author varchar(255) not null,
quantity int not null,
idcategory varchar(255) not null,
price int not null,
disabled boolean not null,
constraint pk_book_id PRIMARY KEY (id),
constraint fk_book_id FOREIGN KEY (categoryId)
REFERENCES category(id)
);
insert into book(idbuku, title, author, quantity, idcategory, price, disabled)
values ('b001', 'buku algoritma', 'dickanirwansyah', 19, 'c0001', 19000, true); | true |
630b942617799f0d23e2a7245567def60fe92716 | SQL | ITSaninho/Casa | /db.sql | UTF-8 | 8,359 | 3.078125 | 3 | [
"MIT"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 07, 2018 at 10:50 AM
-- Server version: 5.7.11-0ubuntu6
-- PHP Version: 7.0.4-7ubuntu2
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: `case`
--
-- --------------------------------------------------------
--
-- Table structure for table `action`
--
CREATE TABLE `action` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `action`
--
INSERT INTO `action` (`id`, `name`) VALUES
(1, 'поповнення'),
(2, 'витрати');
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2018_07_06_135009_create_transaction_table', 1),
(4, '2018_07_06_135105_create_action_table', 1),
(5, '2018_07_06_135143_create_payment_table', 1),
(6, '2018_07_06_135220_create_transaction_category_table', 1),
(7, '2018_07_06_135320_create_transactioncategory_payment_table', 1);
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `payment`
--
CREATE TABLE `payment` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `payment`
--
INSERT INTO `payment` (`id`, `name`) VALUES
(1, 'готівковий'),
(2, 'безготівковий');
-- --------------------------------------------------------
--
-- Table structure for table `transaction`
--
CREATE TABLE `transaction` (
`id` int(10) UNSIGNED NOT NULL,
`transaction_category_id` int(11) NOT NULL,
`paymend_id` int(11) NOT NULL,
`action_id` int(11) NOT NULL,
`price` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `transaction`
--
INSERT INTO `transaction` (`id`, `transaction_category_id`, `paymend_id`, `action_id`, `price`, `created_at`, `updated_at`) VALUES
(1, 1, 1, 1, 3252, '2018-07-06 15:05:11', '2018-07-06 15:05:11'),
(2, 2, 1, 1, 43, '2018-07-06 15:05:13', '2018-07-06 15:05:13'),
(3, 9, 1, 2, 543, '2018-07-06 15:11:11', '2018-07-06 15:11:11'),
(4, 5, 2, 1, 5345, '2018-07-07 03:22:54', '2018-07-07 03:22:54'),
(6, 9, 1, 2, 34, '2018-07-07 03:28:53', '2018-07-07 03:28:53'),
(7, 5, 2, 1, 2332, '2018-07-07 04:40:53', '2018-07-07 04:40:53'),
(8, 11, 2, 2, 43, '2018-07-07 04:43:22', '2018-07-07 04:43:22'),
(10, 1, 1, 1, 65, '2018-07-07 04:45:51', '2018-07-07 04:45:51');
-- --------------------------------------------------------
--
-- Table structure for table `transactioncategory_payment`
--
CREATE TABLE `transactioncategory_payment` (
`id` int(11) NOT NULL,
`transiactioncategory_id` int(11) NOT NULL,
`payment_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `transactioncategory_payment`
--
INSERT INTO `transactioncategory_payment` (`id`, `transiactioncategory_id`, `payment_id`) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 1),
(4, 4, 1),
(5, 5, 2),
(6, 6, 2),
(7, 7, 2),
(8, 8, 1),
(9, 9, 1),
(10, 10, 1),
(11, 10, 2),
(12, 11, 2);
-- --------------------------------------------------------
--
-- Table structure for table `transaction_category`
--
CREATE TABLE `transaction_category` (
`id` int(10) UNSIGNED NOT NULL,
`action_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `transaction_category`
--
INSERT INTO `transaction_category` (`id`, `action_id`, `name`) VALUES
(1, '1', 'готівковий продаж без чеку'),
(2, '1', 'продаж з відправленням товару'),
(3, '1', 'продаж онлайн'),
(4, '1', 'зняття коштів з безготівкового рахунку'),
(5, '1', 'продаж по еквайрингу'),
(6, '1', 'інші поповнення безготівкового рахунку'),
(7, '1', 'поповнення рахунку з безготівкового ГОТІВКОВОГО'),
(8, '2', 'повернення товару'),
(9, '2', 'закупка нового товару'),
(10, '2', 'інші витрати'),
(11, '2', 'послуги банку');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `action`
--
ALTER TABLE `action`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Indexes for table `payment`
--
ALTER TABLE `payment`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `transaction`
--
ALTER TABLE `transaction`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `transactioncategory_payment`
--
ALTER TABLE `transactioncategory_payment`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `transaction_category`
--
ALTER TABLE `transaction_category`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `action`
--
ALTER TABLE `action`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `payment`
--
ALTER TABLE `payment`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `transaction`
--
ALTER TABLE `transaction`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `transactioncategory_payment`
--
ALTER TABLE `transactioncategory_payment`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `transaction_category`
--
ALTER TABLE `transaction_category`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
/*!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 |
8e0e8d1a46b7c56c354b331d1433ea4c9fef2aad | SQL | sharonshlee/LightBnB | /seeds/01_seeds.sql | UTF-8 | 1,435 | 2.796875 | 3 | [] | no_license | -- password: $2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.
INSERT INTO users (name, email, password)
VALUES ('lorem', 'lorem@gmail.com', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'),
('ipsum', 'ipsum@gmail.com', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'),
('hipsum', 'hipsum@gmail.com', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.');
INSERT INTO properties
(owner_id, title, description, thumbnail_photo_url,
cover_photo_url, cost_per_night, parking_spaces, number_of_bathrooms, number_of_bedrooms,
country, street, city, province, post_code)
VALUES (1, 'title', 'description', 'thumbnail_photo_url',
'cover_photo_url', 1, 1, 1, 1,
'country', 'street', 'city', 'province', 'post_code'),
(2, 'title', 'description', 'thumbnail_photo_url',
'cover_photo_url', 2, 3, 3, 3,
'country', 'street', 'city', 'province', 'post_code'),
(3, 'title', 'description', 'thumbnail_photo_url',
'cover_photo_url', 4, 4, 4, 4,
'country', 'street', 'city', 'province', 'post_code');
INSERT INTO reservations (guest_id, property_id, start_date, end_date)
VALUES (1, 1, '2018-09-11', '2018-09-26'),
(2, 2, '2019-01-04', '2019-02-01'),
(3, 3, '2021-10-01', '2021-10-14');
INSERT INTO properties_reviews (property_id, guest_id, reservation_id, message)
VALUES (1, 1, 1, 'message'),
(2, 2, 2, 'message'),
(3, 3, 3, 'message'); | true |
463320c7b115866c626eb1d1aa9dca7ae815e328 | SQL | ben5962/modelisation_planning | /sqlite_crude/respect_vie_privee_we/export.sqlite3.essai_respect_vie_privee.schema.sql | UTF-8 | 6,166 | 3.90625 | 4 | [] | no_license | begin transaction;
drop table if exists periodes_travaillees;
CREATE TABLE periodes_travaillees (
debut_periode timestamp,
fin_periode timestamp CHECK(fin_periode > debut_periode),
jour_travaille DATE,
CONSTRAINT periode_unique UNIQUE(debut_periode, fin_periode, jour_travaille)
);
-- ajout des deux bornes extremes
insert into periodes_travaillees values ('2017-07-01 06:00:00', '2017-07-01 18:00:00', '2017-07-01');
insert into periodes_travaillees values ('2017-08-01 06:00:00', '2017-08-01 18:00:00', '2017-08-01');
-- ajout d une valeur aléatoire qui n est pas un dimanche
insert into periodes_travaillees values ('2017-07-20 06:00:00', '2017-07-20 18:00:00', '2017-07-20');
-- ajout du 8, un samedi et du 10, un lundi(doit sortir le 9 de la liste des dimanches fournis)
insert into periodes_travaillees values ('2017-07-08 06:00:00', '2017-07-08 18:00:00', '2017-07-08');
insert into periodes_travaillees values ('2017-07-10 06:00:00', '2017-07-10 18:00:00', '2017-07-10');
-- ajout du 23, un dimanche (doit sortir le 23 de la liste des dimanches fournis)
insert into periodes_travaillees values ('2017-07-23 06:00:00', '2017-07-23 18:00:00', '2017-07-23');
commit;
drop table if exists dimanches ;
CREATE TABLE dimanches (i integer not null primary key, date_dim TEXT, trim_dim INTEGER);
drop table if exists bornes;
CREATE TABLE bornes (d TEXT not null, f TEXT not null);
pragma recursive_triggers = on;
CREATE TRIGGER ajoutedim BEFORE insert on dimanches
when date(NEW.date_dim) < ( select date(bornes.f) from bornes )
begin
--
-- creation d une serie de dimanches entre deux dates
-- méth : une table contenant un debut et une fin
-- une table contenant le resultat
-- un triggger lance a chaque ajout dans resultat
-- lancant la crea de resultat suivant en util f() de transition au suiv
-- ayant pour cas d arret la borne de fin
-- amorcage : set bornes d, f, set 1er ele de dim comme 1er elem de bornes
--
insert into dimanches (date_dim, trim_dim) values ( date(NEW.date_dim, '+7 day'),
round(
cast(strftime('%m', date(NEW.date_dim, '+7 day')) as FLOAT)
/ 3
+0.4
)
);
end;
-- amorcage de bornes
-- set bornes
-- INSERT INTO "bornes" VALUES('2017-01-01','2017-12-31');
insert into bornes (d,f) select min(date(jour_travaille)), max(date(jour_travaille)) from periodes_travaillees;
-- inset first dim
insert into dimanches (date_dim, trim_dim) select date(bornes.d, 'weekday 0'), round(
cast(strftime('%m', date(bornes.d, 'weekday 0')) as FLOAT) -- mois en flottant
/ 3 -- afin que div à virgule
+ (0.5 - 1.0/3.0 + 0.1) -- ajout de 0,4
)
from bornes -- fin de round
-- fin de values et du insert juste apres.
;
-- les dates de dimanches dispo sont les dates de dim présents ds intervalles et absents de période cp:
begin transaction;
CREATE TABLE periodes_conges (
debut_periode timestamp,
fin_periode timestamp CHECK(fin_periode > debut_periode),
jour_conge DATE,
CONSTRAINT periode_unique UNIQUE(debut_periode, fin_periode, jour_conge)
);
-- ajout du dim 30 comme cp, doit sortir le 30 de la liste des dimanches fournis
insert into periodes_conges values ('2017-07-30 00:00:00', '2017-07-31 00:00:00', '2017-07-30');
commit;
drop view if exists dim_dispo;
create view dim_dispo as select date_dim, trim_dim, periodes_conges.jour_conge from dimanches
left outer join periodes_conges
on dimanches.date_dim = periodes_conges.jour_conge
where periodes_conges.jour_conge is NULL;
-- les dates de dimanches fournis sont les dates de dim
-- non travailles et (ou (jour prec) non travaille ou joursuiv non travaille)
-- et non cp
drop view if exists dim_fournis;
create view dim_fournis as select date_dim, trim_dim, periodes_conges.jour_conge,
periodes_travaillees.jour_travaille, periodes_trav_sam.jour_travaille, periodes_trav_lun.jour_travaille
from dimanches
left outer join periodes_conges
on dimanches.date_dim = periodes_conges.jour_conge
left outer join periodes_travaillees
on dimanches.date_dim = periodes_travaillees.jour_travaille
left outer join periodes_travaillees as periodes_trav_sam
on date(dimanches.date_dim, '-1 day') = periodes_trav_sam.jour_travaille
left outer join periodes_travaillees as periodes_trav_lun
on date(dimanches.date_dim, '+1 day') = periodes_trav_lun.jour_travaille
where periodes_conges.jour_conge is NULL and periodes_travaillees.jour_travaille is NULL
and (periodes_trav_sam.jour_travaille is NULL or periodes_trav_lun.jour_travaille is NULL);
-- la vue joignant tout cela , juste avant le décompte:
drop view if exists dim_vie_priv;
create view dim_vie_priv as
select dimanches.date_dim as existant,
dimanches.trim_dim as num_trimestre,
dim_dispo.date_dim as dim_dispo,
dim_fournis.date_dim as dim_fournis
from dimanches
left outer join dim_dispo
on dimanches.date_dim = dim_dispo.date_dim
left outer join dim_fournis
on dimanches.date_dim = dim_fournis.date_dim;
-- le décompte
drop view if exists decompte_dim_vie_priv;
create view decompte_dim_vie_priv as
select count (dim_vie_priv.existant) as ex, count(dim_vie_priv.dim_dispo) as dispo,
count (dim_vie_priv.dim_fournis) as fournis, round((count(dim_vie_priv.dim_dispo) / 2.0) + 0.49) as dus,
round((count(dim_vie_priv.dim_dispo) / 2.0) + 0.49) -
from dim_vie_priv
group by dim_vie_priv.num_trimestre; | true |
4c6e3d8866d4001c9456d671acf37d935812fd2e | SQL | joshforester/rdboard | /src/sql/init/COURSE.sql | UTF-8 | 1,375 | 3.109375 | 3 | [
"MIT"
] | permissive | SET FOREIGN_KEY_CHECKS=0;
CREATE TABLE `leaderboard`.`COURSE` (
`id` INTEGER UNSIGNED NOT NULL,
`event_id` INTEGER UNSIGNED NOT NULL,
`name` VARCHAR(64) NOT NULL DEFAULT 'default',
`type` ENUM('default','rogaine','weightedrogaine','modifiedrogaine','pointtopoint','stage') NOT NULL DEFAULT 'default',
`length_hours` SMALLINT UNSIGNED DEFAULT 0,
`length_miles` SMALLINT UNSIGNED DEFAULT 0,
`description` text,
`scribblelive_id` VARCHAR(7) NOT NULL DEFAULT `default`,
`coveritlive_id` VARCHAR(10) NOT NULL DEFAULT `default`,
`feedburner_all_id` VARCHAR(64) NOT NULL DEFAULT `default`,
`feedburner_blogs_id` VARCHAR(64) NOT NULL DEFAULT `default`,
`feedburner_photos_id` VARCHAR(64) NOT NULL DEFAULT `default`,
`feedburner_videos_id` VARCHAR(64) NOT NULL DEFAULT `default`,
`feedburner_audio_id` VARCHAR(64) NOT NULL DEFAULT `default`,
`competitor_gmap_suffix` VARCHAR(1024) NOT NULL DEFAULT `default`,
`is_deleted` ENUM('default','no','yes') NOT NULL DEFAULT 'no',
PRIMARY KEY(`id`),
KEY(`event_id`,`name`),
CONSTRAINT `COURSE_event_id_fkc` FOREIGN KEY `COURSE_event_id_fkc` (`event_id`)
REFERENCES `EVENT` (`id`)
ON DELETE RESTRICT
ON UPDATE CASCADE,
CONSTRAINT `COURSE_id_fkc` FOREIGN KEY `COURSE_id_fkc` (`id`)
REFERENCES `DATA_RESOURCE` (`id`)
ON DELETE RESTRICT
ON UPDATE CASCADE
)
TYPE = InnoDB;
| true |
6fdaa32ab69b06077bfd6ecfa556e3922af6383f | SQL | lukaszgryglicki/old_c | /DBklasa/Morgoth.SQL | UTF-8 | 4,979 | 3.15625 | 3 | [
"Apache-2.0"
] | permissive | --
-- PostgreSQL database dump
--
SET SESSION AUTHORIZATION 'morgoth';
--
-- TOC entry 3 (OID 2200)
-- Name: public; Type: ACL; Schema: -; Owner: morgoth
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT ALL ON SCHEMA public TO PUBLIC;
SET search_path = public, pg_catalog;
--
-- TOC entry 4 (OID 17492)
-- Name: klasa_seq; Type: SEQUENCE; Schema: public; Owner: morgoth
--
CREATE SEQUENCE klasa_seq
INCREMENT BY 1
NO MAXVALUE
MINVALUE 0
CACHE 1;
--
-- TOC entry 6 (OID 17494)
-- Name: przedmiot_seq; Type: SEQUENCE; Schema: public; Owner: morgoth
--
CREATE SEQUENCE przedmiot_seq
INCREMENT BY 1
NO MAXVALUE
MINVALUE 0
CACHE 1;
--
-- TOC entry 8 (OID 17496)
-- Name: uczen_seq; Type: SEQUENCE; Schema: public; Owner: morgoth
--
CREATE SEQUENCE uczen_seq
INCREMENT BY 1
NO MAXVALUE
MINVALUE 0
CACHE 1;
--
-- TOC entry 10 (OID 17498)
-- Name: ocena_seq; Type: SEQUENCE; Schema: public; Owner: morgoth
--
CREATE SEQUENCE ocena_seq
START WITH 0
INCREMENT BY 1
NO MAXVALUE
MINVALUE 0
CACHE 1;
--
-- TOC entry 12 (OID 17513)
-- Name: przedmiot; Type: TABLE; Schema: public; Owner: morgoth
--
CREATE TABLE przedmiot (
nazwa text NOT NULL,
idprzedmiotu integer DEFAULT nextval('"przedmiot_seq"'::text) NOT NULL
);
--
-- TOC entry 13 (OID 17521)
-- Name: klasa; Type: TABLE; Schema: public; Owner: morgoth
--
CREATE TABLE klasa (
nazwa text NOT NULL,
idklasy integer DEFAULT nextval('"klasa_seq"'::text) NOT NULL
);
--
-- TOC entry 14 (OID 17526)
-- Name: uczen; Type: TABLE; Schema: public; Owner: morgoth
--
CREATE TABLE uczen (
imie text NOT NULL,
nazwisko text NOT NULL,
idklasy integer NOT NULL,
iducznia integer DEFAULT nextval('"uczen_seq"'::text) NOT NULL
);
--
-- TOC entry 15 (OID 17579)
-- Name: ocena; Type: TABLE; Schema: public; Owner: morgoth
--
CREATE TABLE ocena (
ocena real NOT NULL,
czyliczona boolean NOT NULL,
iducznia integer NOT NULL,
idprzedmiotu integer NOT NULL,
idoceny integer DEFAULT nextval('"ocena_seq"'::text) NOT NULL
);
--
-- Data for TOC entry 20 (OID 17513)
-- Name: przedmiot; Type: TABLE DATA; Schema: public; Owner: morgoth
--
COPY przedmiot (nazwa, idprzedmiotu) FROM stdin;
\.
--
-- Data for TOC entry 21 (OID 17521)
-- Name: klasa; Type: TABLE DATA; Schema: public; Owner: morgoth
--
COPY klasa (nazwa, idklasy) FROM stdin;
\.
--
-- Data for TOC entry 22 (OID 17526)
-- Name: uczen; Type: TABLE DATA; Schema: public; Owner: morgoth
--
COPY uczen (imie, nazwisko, idklasy, iducznia) FROM stdin;
\.
--
-- Data for TOC entry 23 (OID 17579)
-- Name: ocena; Type: TABLE DATA; Schema: public; Owner: morgoth
--
COPY ocena (ocena, czyliczona, iducznia, idprzedmiotu, idoceny) FROM stdin;
\.
--
-- TOC entry 16 (OID 17519)
-- Name: przedmiot_pkey; Type: CONSTRAINT; Schema: public; Owner: morgoth
--
ALTER TABLE ONLY przedmiot
ADD CONSTRAINT przedmiot_pkey PRIMARY KEY (idprzedmiotu);
--
-- TOC entry 17 (OID 17524)
-- Name: klasa_pkey; Type: CONSTRAINT; Schema: public; Owner: morgoth
--
ALTER TABLE ONLY klasa
ADD CONSTRAINT klasa_pkey PRIMARY KEY (idklasy);
--
-- TOC entry 18 (OID 17532)
-- Name: uczen_pkey; Type: CONSTRAINT; Schema: public; Owner: morgoth
--
ALTER TABLE ONLY uczen
ADD CONSTRAINT uczen_pkey PRIMARY KEY (iducznia);
--
-- TOC entry 19 (OID 17582)
-- Name: ocena_pkey; Type: CONSTRAINT; Schema: public; Owner: morgoth
--
ALTER TABLE ONLY ocena
ADD CONSTRAINT ocena_pkey PRIMARY KEY (idoceny);
--
-- TOC entry 24 (OID 17534)
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: morgoth
--
ALTER TABLE ONLY uczen
ADD CONSTRAINT "$1" FOREIGN KEY (idklasy) REFERENCES klasa(idklasy) ON DELETE CASCADE;
--
-- TOC entry 25 (OID 17584)
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: morgoth
--
ALTER TABLE ONLY ocena
ADD CONSTRAINT "$1" FOREIGN KEY (iducznia) REFERENCES uczen(iducznia) ON DELETE CASCADE;
--
-- TOC entry 26 (OID 17588)
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: morgoth
--
ALTER TABLE ONLY ocena
ADD CONSTRAINT "$2" FOREIGN KEY (idprzedmiotu) REFERENCES przedmiot(idprzedmiotu) ON DELETE CASCADE;
--
-- TOC entry 5 (OID 17492)
-- Name: klasa_seq; Type: SEQUENCE SET; Schema: public; Owner: morgoth
--
SELECT pg_catalog.setval('klasa_seq', 5, true);
--
-- TOC entry 7 (OID 17494)
-- Name: przedmiot_seq; Type: SEQUENCE SET; Schema: public; Owner: morgoth
--
SELECT pg_catalog.setval('przedmiot_seq', 6, true);
--
-- TOC entry 9 (OID 17496)
-- Name: uczen_seq; Type: SEQUENCE SET; Schema: public; Owner: morgoth
--
SELECT pg_catalog.setval('uczen_seq', 14, true);
--
-- TOC entry 11 (OID 17498)
-- Name: ocena_seq; Type: SEQUENCE SET; Schema: public; Owner: morgoth
--
SELECT pg_catalog.setval('ocena_seq', 0, false);
--
-- TOC entry 2 (OID 2200)
-- Name: SCHEMA public; Type: COMMENT; Schema: -; Owner: morgoth
--
COMMENT ON SCHEMA public IS 'Standard public schema';
| true |
fc280f7a814964832161b2c3c67d8a70217ab2d6 | SQL | diolektor/torrentpier | /install/sql/ocelot.sql | UTF-8 | 2,134 | 2.9375 | 3 | [
"MIT"
] | permissive | SET SQL_MODE = "";
-- ----------------------------
-- Table structure for `bb_bt_tracker`
-- ----------------------------
DROP TABLE IF EXISTS `bb_bt_tracker`;
CREATE TABLE IF NOT EXISTS `bb_bt_tracker` (
`peer_hash` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
`peer_id` varchar(20) NOT NULL,
`user_id` mediumint(9) NOT NULL DEFAULT '0',
`ip` varchar(42) NOT NULL DEFAULT '0',
`ipv6` varchar(32) DEFAULT NULL,
`port` smallint(5) unsigned NOT NULL DEFAULT '0',
`client` varchar(51) NOT NULL DEFAULT 'Unknown',
`seeder` tinyint(1) NOT NULL DEFAULT '0',
`releaser` tinyint(1) NOT NULL DEFAULT '0',
`tor_type` tinyint(1) NOT NULL DEFAULT '0',
`uploaded` bigint(20) unsigned NOT NULL DEFAULT '0',
`downloaded` bigint(20) unsigned NOT NULL DEFAULT '0',
`remain` bigint(20) unsigned NOT NULL DEFAULT '0',
`speed_up` mediumint(8) unsigned NOT NULL DEFAULT '0',
`speed_down` mediumint(8) unsigned NOT NULL DEFAULT '0',
`up_add` bigint(20) unsigned NOT NULL DEFAULT '0',
`down_add` bigint(20) unsigned NOT NULL DEFAULT '0',
`update_time` int(11) NOT NULL DEFAULT '0',
`complete_percent` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`peer_hash`),
KEY `topic_id` (`topic_id`),
KEY `user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of bb_bt_tracker
-- ----------------------------
-- ----------------------------
-- Table structure for `bb_bt_tracker_snap`
-- ----------------------------
DROP TABLE IF EXISTS `bb_bt_tracker_snap`;
CREATE TABLE IF NOT EXISTS `bb_bt_tracker_snap` (
`topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
`seeders` mediumint(8) unsigned NOT NULL DEFAULT '0',
`leechers` mediumint(8) unsigned NOT NULL DEFAULT '0',
`speed_up` int(10) unsigned NOT NULL DEFAULT '0',
`speed_down` int(10) unsigned NOT NULL DEFAULT '0',
`complete` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`topic_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of bb_bt_tracker_snap
-- ----------------------------
| true |
e25235f7398400d21710238a20f012394de12d01 | SQL | MohamedMedina/SamDb | /com.idemia.sam.be.DB_Management/StoredProcedures/InsertWorkField.Sql | UTF-8 | 926 | 2.875 | 3 | [] | no_license |
--------------------------------------------------------------------------------------------------------------------
-- Created By :
-- Created Date : 2019/11/19 04:32:47 م
--------------------Change History----------------------------------------------------------------------------------
-- Change No Date Time Author Descrition
--------------------Change History----------------------------------------------------------------------------------
-- Name : [Lookups].[InsertWorkField]
-- Description: Insert Row Into [Lookups].[WorkField]
--------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [Lookups].[InsertWorkField]
(
@Id AS INT OUTPUT,
@name AS NVARCHAR(60),
@nameAr AS NVARCHAR(60)
) AS
BEGIN
INSERT INTO [Lookups].[WorkField]
(
[name],
[nameAr]
)
VALUES
(
@name,
@nameAr
)
SELECT @Id = SCOPE_IDENTITY()
END
| true |
110287f762f116a881e5c6ff8f19a8daec8768d3 | SQL | ria55/JavaWithDB | /src/main/resources/dragonDB_script.sql | UTF-8 | 885 | 3.84375 | 4 | [] | no_license | DROP DATABASE IF EXISTS dragonDB;
CREATE DATABASE /* IF NOT EXISTS */ dragonDB;
USE dragonDB;
/* DROP TABLE IF EXISTS dragon */
CREATE TABLE /* IF NOT EXISTS */ dragon (
id INT UNSIGNED AUTO_INCREMENT,
unique_name VARCHAR(100) UNIQUE,
dragon_text LONGTEXT,
rarity ENUM('common','rare','very rare','epic','legendary','heroic'),
design LONGBLOB,
PRIMARY KEY (id)
);
/* DROP TABLE IF EXISTS element */
CREATE TABLE /* IF NOT EXISTS */ element (
element_name VARCHAR(50),
icon_img BLOB,
PRIMARY KEY (element_name)
);
/* DROP TABLE IF EXISTS dragons_element */
CREATE TABLE /* IF NOT EXISTS */ dragons_element (
id INT UNSIGNED AUTO_INCREMENT,
dragon_id INT UNSIGNED,
element_name VARCHAR(50),
PRIMARY KEY (id),
FOREIGN KEY (dragon_id) REFERENCES dragon(id),
FOREIGN KEY (element_name) REFERENCES element(element_name)
);
| true |
258214953d1f21dd2a32fea6e63960bc72cb5349 | SQL | cfdxkk/tryShoppingSystem_JAVA_JDBC | /ShoppingSystem_JDBC_Java/createDatabase.sql | UTF-8 | 4,694 | 3.328125 | 3 | [
"CC0-1.0"
] | permissive | CREATE DATABASE test3;
USE test3;
/*
Navicat MySQL Data Transfer
Source Server : localhost-root
Source Server Type : MySQL
Source Server Version : 50729
Source Host : localhost:3306
Source Schema : purchase
Target Server Type : MySQL
Target Server Version : 50729
File Encoding : 65001
Date: 01/12/2020 23:39:44
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for goods
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`goodsid` int(11) NOT NULL,
`goodsname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`price` decimal(10, 2) NULL DEFAULT NULL,
`typeid` int(11) NULL DEFAULT NULL,
`supplyid` int(11) NULL DEFAULT NULL,
`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`goodsid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES (1, 'Lenovo/联想 YOGA710 -14ISK', 5400.00, 1, 1, 'CPU:英特尔 酷睿 i5-7200U,内存:4G,硬盘:固态256G,颜色:银色');
INSERT INTO `goods` VALUES (2, 'HP PROBOOK440', 5200.00, 1, 2, 'CPU:英特尔 酷睿 i5-7200U,内存:8G,硬盘:固态512G,颜色:酒红色');
INSERT INTO `goods` VALUES (3, '2020耐克秋冬运动休闲跑步套装', 980.00, 2, 3, '类型:男装,颜色:暗红色、黑色、深蓝色,型号:(M-4XL)');
INSERT INTO `goods` VALUES (4, '2021春季亲子运动套装', 1115.00, 2, 4, '类型:亲子装,颜色:橘色、灰色,型号:(L-3XL & M-2XL)');
-- ----------------------------
-- Table structure for goodstype
-- ----------------------------
DROP TABLE IF EXISTS `goodstype`;
CREATE TABLE `goodstype` (
`typeid` int(11) NOT NULL,
`typename` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`typeid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of goodstype
-- ----------------------------
INSERT INTO `goodstype` VALUES (1, '电脑');
INSERT INTO `goodstype` VALUES (2, '衣服');
-- ----------------------------
-- Table structure for orders
-- ----------------------------
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
`orderid` int(11) NOT NULL AUTO_INCREMENT,
`goodsid` int(11) NULL DEFAULT NULL,
`count` int(11) NULL DEFAULT NULL,
`sum` decimal(10, 2) NULL DEFAULT NULL,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`orderid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for supply
-- ----------------------------
DROP TABLE IF EXISTS `supply`;
CREATE TABLE `supply` (
`supplyid` int(11) NOT NULL,
`supplier` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`telephone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`supplyid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of supply
-- ----------------------------
INSERT INTO `supply` VALUES (1, '联想天晴东方专卖店', '中国北京', '010-87654321');
INSERT INTO `supply` VALUES (2, 'HP大连专卖店', '中国大连', '0411-84830000');
INSERT INTO `supply` VALUES (3, '耐克西城专卖店', '中国沈阳', '024-87654321');
INSERT INTO `supply` VALUES (4, '阿迪达斯东城专卖店', '中国北京', '010-88776655');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`realname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`username`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('zhangsan', '11', '张三');
SET FOREIGN_KEY_CHECKS = 1; | true |
f615de430bbe1aaaa256668b0f8c02faa1eb1490 | SQL | Ensembl/ensembl-variation | /sql/patch_67_68_c.sql | UTF-8 | 5,383 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | -- Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
-- Copyright [2016-2023] EMBL-European Bioinformatics Institute
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
## change consequence_type columns in transcript_variation and variation_feature
## TRANSCRIPT VARIATION
# create tmp table
CREATE TABLE tmp_tv LIKE transcript_variation;
# alter its consequence type field
ALTER TABLE tmp_tv CHANGE consequence_types consequence_types SET('splice_acceptor_variant','splice_donor_variant','stop_lost','coding_sequence_variant','missense_variant','stop_gained','synonymous_variant','frameshift_variant','nc_transcript_variant','non_coding_exon_variant','mature_miRNA_variant','NMD_transcript_variant','5_prime_UTR_variant','3_prime_UTR_variant','incomplete_terminal_codon_variant','intron_variant','splice_region_variant','downstream_gene_variant','upstream_gene_variant','initiator_codon_variant','stop_retained_variant','inframe_insertion','inframe_deletion','transcript_ablation','transcript_fusion','transcript_amplification','transcript_translocation','TFBS_ablation','TFBS_fusion','TFBS_amplification','TFBS_translocation','regulatory_region_ablation','regulatory_region_fusion','regulatory_region_amplification','regulatory_region_translocation','feature_elongation','feature_truncation') DEFAULT NULL;
# insert into tmp table, replacing old terms with new as we go
INSERT INTO tmp_tv SELECT transcript_variation_id, variation_feature_id, feature_stable_id, allele_string, somatic,
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(consequence_types,
'non_synonymous_codon', 'missense_variant'),
'synonymous_codon', 'synonymous_variant'),
'initiator_codon_change', 'initiator_codon_variant'),
'inframe_codon_loss', 'inframe_deletion'),
'inframe_codon_gain', 'inframe_insertion'),
'5KB_downstream_variant', 'downstream_gene_variant'),
'500B_downstream_variant', 'downstream_gene_variant'),
'5KB_upstream_variant', 'upstream_gene_variant'),
'2KB_upstream_variant', 'upstream_gene_variant'),
cds_start, cds_end, cdna_start, cdna_end, translation_start, translation_end, codon_allele_string, pep_allele_string, hgvs_genomic, hgvs_transcript, hgvs_protein, polyphen_prediction, polyphen_score, sift_prediction, sift_score
FROM transcript_variation;
DROP TABLE transcript_variation;
RENAME TABLE tmp_tv TO transcript_variation;
## VARIATION_FEATURE
# create tmp table
CREATE TABLE tmp_vf LIKE variation_feature;
# alter its consequence type field
ALTER TABLE tmp_vf CHANGE consequence_type consequence_type SET('intergenic_variant','splice_acceptor_variant','splice_donor_variant','stop_lost','coding_sequence_variant','missense_variant','stop_gained','synonymous_variant','frameshift_variant','nc_transcript_variant','non_coding_exon_variant','mature_miRNA_variant','NMD_transcript_variant','5_prime_UTR_variant','3_prime_UTR_variant','incomplete_terminal_codon_variant','intron_variant','splice_region_variant','downstream_gene_variant','upstream_gene_variant','initiator_codon_variant','stop_retained_variant','inframe_insertion','inframe_deletion','transcript_ablation','transcript_fusion','transcript_amplification','transcript_translocation','TFBS_ablation','TFBS_fusion','TFBS_amplification','TFBS_translocation','regulatory_region_ablation','regulatory_region_fusion','regulatory_region_amplification','regulatory_region_translocation','feature_elongation','feature_truncation') NOT NULL DEFAULT 'intergenic_variant';
# insert into tmp table, replacing old terms with new as we go
INSERT INTO tmp_vf SELECT variation_feature_id, seq_region_id, seq_region_start, seq_region_end, seq_region_strand, variation_id, allele_string, variation_name, map_weight, flags, source_id, validation_status,
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(consequence_type,
'non_synonymous_codon', 'missense_variant'),
'synonymous_codon', 'synonymous_variant'),
'initiator_codon_change', 'initiator_codon_variant'),
'inframe_codon_loss', 'inframe_deletion'),
'inframe_codon_gain', 'inframe_insertion'),
'5KB_downstream_variant', 'downstream_gene_variant'),
'500B_downstream_variant', 'downstream_gene_variant'),
'5KB_upstream_variant', 'upstream_gene_variant'),
'2KB_upstream_variant', 'upstream_gene_variant'),
variation_set_id, class_attrib_id, somatic
FROM variation_feature;
DROP TABLE variation_feature;
RENAME TABLE tmp_vf TO variation_feature;
# patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL,'patch', 'patch_67_68_c.sql|change consequence_type sets in transcript_variation and variation_feature');
| true |
980f1e65fc54fca847d3b3f399bc8790ea572591 | SQL | XClouded/avp | /agp-core/src/main/resources/sql/reports/significantactionsreport.sql | UTF-8 | 1,822 | 3.796875 | 4 | [] | no_license | SELECT
SAD.ACTIONTIMESTAMP AT LOCAL AS SAD_ACTIONTIMESTAMP
, OP.USERNAME AS OP_USERNAME
, OP.FIRSTNAME AS OP_FIRSTNAME
, OP.LASTNAME AS OP_LASTNAME
, SAD.ACTIONCODE AS SAD_ACTIONCODE
, SAD.ACTIONTYPE AS SAD_ACTIONTYPE
, E.SPORTCODE AS E_SPORTCODE
, E.ID AS E_ID
, E.DESCRIPTION AS E_DESCRIPTION
, E.EVENTTYPEID AS E_EVENTTYPEID
, E.STARTTIME AT LOCAL AS E_STARTTIME
, ET.PERIODID AS ET_PERIODID
, ET.EVENTTOTALSTYPEID AS ET_EVENTTOTALSTYPEID
, M.ID AS M_ID
, M.DESCRIPTION AS M_DESCRIPTION
, M.PERIODID AS M_PERIODID
, OC.DESCRIPTION AS OC_DESCRIPTION
, OC.RESULTINYN AS OC_RESULTINYN
, A.USERNAME AS A_USERNAME
, A.FIRSTNAME AS A_FIRSTNAME
, A.LASTNAME AS A_LASTNAME
, S.DESCRIPTION AS S_DESCRIPTION
, TR.DESCRIPTION AS TR_DESCRIPTION
, TI.DESCRIPTION AS TI_DESCRIPTION
, TR.BETSLIPID AS TR_BETSLIPID
, C.BETSLIPID AS C_BETSLIPID
, C.DESCRIPTION AS C_DESCRIPTION
, SAD.CHANGES AS SAD_CHANGES
FROM
/*=SCHEMA*/SADATA SAD
INNER JOIN /*=SCHEMA*/ACCOUNTS OP ON (SAD.OPERATORID = OP.ID)
LEFT OUTER JOIN /*=SCHEMA*/EVENTS E ON (SAD.EVENTID = E.ID)
LEFT OUTER JOIN /*=SCHEMA*/MARKETS M ON (SAD.MARKETID = M.ID)
LEFT OUTER JOIN /*=SCHEMA*/OUTCOMES OC ON (SAD.OUTCOMEID = OC.ID)
LEFT OUTER JOIN /*=SCHEMA*/EVENTTOTALS ET ON (SAD.EVENTTOTALID = ET.ID)
LEFT OUTER JOIN /*=SCHEMA*/PERIODS P ON (ET.PERIODID = P.ID)
LEFT OUTER JOIN /*=SCHEMA*/PERIODTYPES PT ON (P.PERIODTYPEID = PT.ID)
LEFT OUTER JOIN /*=SCHEMA*/ACCOUNTS A ON (SAD.ACCOUNTID = A.ID)
LEFT OUTER JOIN /*=SCHEMA*/TRANSACTIONS TR ON (SAD.TRANSACTIONID = TR.ID)
LEFT OUTER JOIN /*=SCHEMA*/TILLS TI ON (SAD.TILLID = TI.ID)
LEFT OUTER JOIN /*=SCHEMA*/SHOPS S ON (A.ID = S.ACCOUNTID)
LEFT OUTER JOIN /*=SCHEMA*/CASHLEDGER C ON (SAD.CASHLEDGERID = C.ID) | true |
4bf0c029794881fc50aebbf841d6999bba2e0604 | SQL | FirebirdSQL/x-cvs-vulcanj | /VulcanJ/ddl/nist/flg006.sql | UTF-8 | 1,029 | 3.28125 | 3 | [] | no_license | SET NAMES ASCII;
CREATE DATABASE 'test.fdb' DEFAULT CHARACTER SET ISO8859_1;
-- TEST:0299 FIPS Flagger - identifier length > 18!
-- NOTE: OPTIONAL FIPS Flagger test
-- FIPS Flagger Test. Support for this feature is not required.
-- If supported, this feature must be flagged as an extension to the
-- standard.
-- NOTE:0299 Delete any SQL statement which causes
-- NOTE:0299 this procedure to abort. But, there
-- NOTE:0299 is no need to remove a statement with a warning.
CREATE TABLE TABLEFGHIJKLMNOPQ19 (COL2 INTEGER);
CREATE TABLE SHORTTABLE (COLUMN123456789IS19 INTEGER);
CREATE TABLE BASETABLE1 (COL1 INTEGER);
CREATE VIEW VIEWABCDEFGHIKLMN19 (COL3) AS SELECT COL1 FROM BASETABLE1;
INSERT INTO TABLEFGHIJKLMNOPQ19 VALUES (299);
INSERT INTO SHORTTABLE VALUES (299);
INSERT INTO BASETABLE1 VALUES (299);
SELECT COL2 FROM TABLEFGHIJKLMNOPQ19;
SELECT COLUMN123456789IS19 FROM SHORTTABLE;
SELECT COL3 FROM VIEWABCDEFGHIKLMN19;
-- PASS:0299 If the value 299 is selected by any of SQL SELECTs above?
DROP DATABASE;
| true |
cd81c501eed53c65cf8a06636aaa544d959694f3 | SQL | Naoufal1221/Habilitations | /src/main/resources/static/portail_base/portail_societe_utilisateur.sql | UTF-8 | 2,802 | 3.203125 | 3 | [] | no_license | -- MySQL dump 10.13 Distrib 8.0.16, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: portail_societe
-- ------------------------------------------------------
-- Server version 5.7.24
/*!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 utf8 ;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `utilisateur`
--
DROP TABLE IF EXISTS `utilisateur`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `utilisateur` (
`id` bigint(20) NOT NULL,
`societe` bigint(20) NOT NULL,
`created_by` varchar(255) DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
`last_modifed_date` datetime DEFAULT NULL,
`last_modified_by` varchar(255) DEFAULT NULL,
`login` varchar(255) NOT NULL,
`nom` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`prenom` varchar(255) NOT NULL,
`statut` varchar(255) NOT NULL,
`tel` varchar(255) DEFAULT NULL,
`entite` bigint(20) NOT NULL,
`profil` bigint(20) NOT NULL,
PRIMARY KEY (`id`,`societe`),
KEY `FKo07f1onhugpad9qf584kq0bes` (`societe`),
CONSTRAINT `FKo07f1onhugpad9qf584kq0bes` FOREIGN KEY (`societe`) REFERENCES `societe` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `utilisateur`
--
LOCK TABLES `utilisateur` WRITE;
/*!40000 ALTER TABLE `utilisateur` DISABLE KEYS */;
INSERT INTO `utilisateur` VALUES (44,4,'SYSTEM','2021-06-14 13:55:07',NULL,NULL,'omar.azami@gmail.com','AZAMI','$2a$10$pUpqnyN8FAI3OeEh6VtE5uU/iImpj0blI5yYLNIB3vEdmGEWyvaW2','OMAR','public','0623061248',37,13),(45,4,'SYSTEM','2021-06-14 13:56:20',NULL,NULL,'naoufal.sarf97@gmail.com','SARF','$2a$10$4SpGMEdyyOTbkeny6YCRmeYJyDc2BCCuzqu3RohYgjUVY6RoRqWNu','NAOUFAL','public','0623061248',37,13);
/*!40000 ALTER TABLE `utilisateur` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2021-06-14 15:14:42
| true |
65ccd609bd152780561e0272f87f4ee132dd9883 | SQL | whawkins4/arborlibrary | /db/circ/repeatableScripts/newBooks.sql | UTF-8 | 4,348 | 3.78125 | 4 | [] | no_license | -- Table: books
DROP TABLE book_import;
CREATE TABLE book_import
(
timestamp character varying
, accession character varying
, dewey character varying
, cutter character varying
, copy character varying
, last character varying
, first character varying
, middle character varying
, title character varying
, subtitle character varying
, series character varying
, number character varying,
format character varying,
isbn character varying,
lccn character varying,
publisher character varying,
place character varying,
copyright character varying,
illustrated character varying,
type character varying,
pages character varying,
contributor1 character varying,
contributor2 character varying,
contributor3 character varying,
subject1 character varying,
subject2 character varying,
subject3 character varying,
subject4 character varying,
subject5 character varying,
subject6 character varying,
subject7 character varying,
subject8 character varying,
summary character varying,
collection character varying,
price character varying,
source character varying,
awards_publicity character varying
)
WITH (
OIDS=FALSE
);
ALTER TABLE book_import
OWNER TO libraryadmin;
COPY book_import from '/Users/administrator/arborlibrary/db/circ/drop/newbooks.csv' with csv;
delete from book_import where timestamp = 'timestamp';
delete from book_import where accession in (select cast(accession as character varying) from copies);
delete from book_import where length(accession)<>8;
update book_import set isbn = trim(isbn);
insert into books (date, title, series, format, isbn, lccn, copyright, illustrated, illus_type, pages,
subject1, subject2, subject3, subject4, notes1, notes2, notes3, summary, awards_publicity)
select timestamp, trim(title), series, format, trim(isbn), lccn, copyright, illustrated, type, pages,
subject1, subject2, subject3, subject4, contributor1, contributor2, contributor3, summary, awards_publicity from book_import
where trim(isbn) not in (select trim(isbn) from books);
/* at this stage in the process manually mark any duplicated isbns frm the new data with a D- prefix in one of them before proceeding to the next script */
/*
//dup isbns can hurt
select * from book_import where isbn in (select isbn from books group by isbn having count(*)>1)
*/
insert into copies (book_id,catalog_date,copy_number, collection, source, accession,dewey, cutter)
select b.id, i.timestamp, i.copy, i.collection, i.source, cast(i.accession as integer),dewey, cutter
from book_import i join books b on trim(i.isbn) = trim(b.isbn)
where not exists (select * from copies c where c.accession = cast(i.accession as integer));
update book_import set last = trim(coalesce(last,''));
update book_import set first = trim(coalesce(first,''));
update book_import set middle = trim(coalesce(middle,''));
insert into authors (auth_last, auth_first, auth_middle)
select distinct last, first, middle from book_import i
where not exists (select * from authors a where auth_last = last and auth_middle=middle and auth_first = first);
insert into authors_books(book_id,author_id, authorship_type)
select b.id, a.id, 0 from books b join book_import i on b.isbn = i.isbn
join authors a on a.auth_last = i.last and a.auth_middle=i.middle and a.auth_first = i.first
where not exists (select * from authors_books where book_id = b.id and author_id = a.id);
update book_import set publisher = regexp_replace(trim(coalesce(publisher,'')), ',$',''),place = regexp_replace(trim(coalesce(place,'')), ',$','');
insert into publishers (pub_name, pub_place)
select distinct publisher, place from book_import where not exists (select * from publishers where pub_name = publisher and pub_place = place);
update books set publisher_id = s.pubid
from
( select o.isbn, p.id as pubid from book_import o join publishers p on o.publisher = p.pub_name and o.place = p.pub_place ) s
where books.isbn = s.isbn
and books.publisher_id is null;
---notes
--copies 87560 is the highest copyid before we start importing these new books
-- bookds 122608
-- authors 81664
--publishers 67242
--select * into cleanup_books_with_dup_isbns from book_import where isbn in (select isbn from books group by isbn having count(*) >1) ;;
--delete from book_import where isbn in (select isbn from books group by isbn having count(*) >1)
| true |
1b135c38e82f6552e33b2d3daa09656b5653461e | SQL | Boomoon/Project | /Housing.sql | UTF-8 | 4,782 | 4.40625 | 4 | [] | no_license | --------------------- CLEANING DATA USING SQL ---------------------
-- Check whether there are missing values for propertyAddress or not
SELECT * from demo.dbo.home
WHERE propertyAddress is null;
-- One ParcelID can have multiple uniqueIDs, so the propertyAddress should not be null
-- We should consider two columns which are uniqueID and parcelID, in order to do that we need to use self join
SELECT a.uniqueID, a.parcelID, a.propertyAddress, b.uniqueID, b.parcelID, b.propertyAddress, isnull(a.propertyAddress,b.propertyAddress) as updatedPropertyAddress
FROM demo.dbo.home as a
JOIN demo.dbo.home as b
ON a.parcelID=b.parcelID and a.uniqueID <> b.uniqueID
WHERE a.propertyAddress is null;
-- Replace Null propertyAddress with the correct value
UPDATE a
SET propertyAddress = isnull(a.propertyAddress,b.propertyaddress)
FROM demo.dbo.home as a
JOIN demo.dbo.home as b
ON a.parcelID=b.parcelID and a.uniqueID <> b.uniqueID
WHERE a.propertyAddress is null;
-- Reheck whether there are missing values for propertyAddress or not
SELECT * from demo.dbo.home
WHERE propertyAddress is null;
-- Breaking propert address into address and city (1808 FOX CHASE DR, GOODLETTSVILLE -> 1808 FOX CHASE DR and GOODLETTSVILLE)
SELECT propertyAddress,
substring(propertyAddress,1,charindex(',',propertyAddress)-1) as Address,
substring(propertyAddress,charindex(',',propertyAddress)+1,len(propertyAddress)) as City
FROM demo.dbo.home;
-- Add two new columns 1)Address 2)City
ALTER TABLE demo.dbo.home
ADD propSplitAddress varchar(255);
UPDATE demo.dbo.home
SET propSplitAddress = substring(propertyAddress,1,charindex(',',propertyAddress)-1);
ALTER TABLE demo.dbo.home
ADD propSplitCity varchar(255);
UPDATE demo.dbo.home
SET propSplitCity = substring(propertyAddress,charindex(',',propertyAddress)+1,len(propertyAddress));
-- Split ownerAddress (1808 FOX CHASE DR, GOODLETTSVILLE, TN --> 1808 FOX CHASE DR and GOODLETTSVILLE and TN)
SELECT OwnerAddress,
PARSENAME(replace(OwnerAddress,',','.'),3) as Address,
PARSENAME(replace(OwnerAddress,',','.'),2) as City,
PARSENAME(replace(OwnerAddress,',','.'),1) as State
FROM demo.dbo.home
-- Add three new columns
ALTER TABLE demo.dbo.home
ADD ownerSplitAddress NVARCHAR(255);
UPDATE demo.dbo.home
SET ownerSplitAddress=parsename(REPLACE(OwnerAddress,',','.'),3)
ALTER TABLE demo.dbo.home
ADD ownerSplitCity NVARCHAR(255);
UPDATE demo.dbo.home
SET ownerSplitCity=parsename(REPLACE(OwnerAddress,',','.'),2)
ALTER TABLE demo.dbo.home
ADD ownerSplitState NVARCHAR(255);
UPDATE demo.dbo.home
SET ownerSplitState =parsename(REPLACE(OwnerAddress,',','.'),1)
-- Count how many soldAsVacant are filled incorrectly
SELECT soldAsVacant, count(*)
FROM demo.dbo.home
GROUP BY soldAsVacant
-- Change Y to Yes and N to No in SoldAsVacant
SELECT soldAsVacant,
CASE WHEN soldAsVacant ='Y' THEN 'YES'
WHEN soldAsVacant ='N' THEN 'NO'
ELSE soldAsVacant
END as updatedValue
FROM demo.dbo.home
-- Update the value Y to Yes and N to No
UPDATE demo.dbo.home
SET SoldAsVacant = CASE WHEN SoldAsVacant = 'Y' THEN 'YES'
WHEN SoldAsVacant = 'N' THEN 'NO'
ELSE SoldAsVacant
END
-- Finding duplicate data (Using partition by to find the duplicate value - if the data is duplicated indexNo will be added)
SELECT *
FROM
(SELECT *,(row_number() over (Partition BY ParcelID,propertyAddress,saleprice,saledate,legalreference
ORDER BY UniqueID)) as indexNo
from demo.dbo.home) as subquery
WHERE subquery.indexNo >1;
-- DROP duplicated data rows
DELETE subquery
FROM
(SELECT *,(row_number() over (Partition BY ParcelID,propertyAddress,saleprice,saledate,legalreference
ORDER BY UniqueID)) as indexNo
from demo.dbo.home) as subquery
WHERE subquery.indexNo >1;
-- Backup table before dropping or deleting the raw data
SELECT * into homeBackup from demo.dbo.housing;
-- Remove unused column
ALTER TABLE demo.dbo.home
DROP COLUMN owneraddress, taxdistrict, propertyaddress
-- Find the average price per Acreage in each city each day
SELECT SaleDate, propSplitCity,
AVG(CAST(AVG(totalValue)/AVG(Acreage) as decimal(16,2))) OVER (PARTITION BY saleDate, propSplitCity) as averagePrice
FROM demo.dbo.home
WHERE totalValue is not null
GROUP BY SaleDate, propSplitCity
ORDER by saledate, propSplitCity;
-- Find the number of house in each owner city
SELECT ownerSplitCity,(count(*)) as countHouse
FROM demo.dbo.home
WHERE ownerSplitCity is not null
GROUP BY ownerSplitcity
-- Using union all to add another row regarding total house in every cities
UNION ALL
select ' SUM' , count(ownerSplitCity)
FROM demo.dbo.home
WHERE ownerSplitCity is not null
| true |
534533825249c4cde9d837a216ff7b14cf3724ae | SQL | bmatney/to-do-list | /database.sql | UTF-8 | 380 | 2.984375 | 3 | [] | no_license | CREATE TABLE tasks(
id SERIAL PRIMARY KEY,
title VARCHAR(80) NOT NULL,
task_content VARCHAR(80) NOT NULL
);
INSERT INTO tasks (title, task_content)
VALUES ('Weekend Challenge', 'Complete the weekend challenge to make a to-do list'),
('Sleep', 'Try to get 8 hours of sleep'),
('Read Book', 'Finally get around to reading the Duckett books that you bought');
SELECT *
FROM tasks;
| true |
064b76492f342dbf189dfedef1922805bdae28c6 | SQL | abealsileshi/MySQL | /HW3/HW3.sql | UTF-8 | 7,931 | 4.59375 | 5 | [] | no_license | use classicmodels;
#1) List in alphabetical order without duplicates the names of the cities in Spain where ClassicModels has customers. (3)
select distinct(city)
from Customers
where country in ('Spain')
Order by city asc;
#2) List the employee id, last name, first name of each employee who works in Paris (use a subquery). (5)
select employeeNumber, lastName, firstName
from Employees
where
officeCode = '4';
#3. List the ProductCode, ProductName, ProductScale, ProductVendor, buyPrice for all products that are in the Motorcycles product line and have a buyPrice greater than 50 and less than 80. (5)
select productCode, productName, productScale, productVendor, buyPrice
from Products
where
productLine = 'motorcycles'
having (buyPrice > 50 && buyPrice < 80);
#4. List the productCode, productName, productLine, quantityInStock, buyPrice for the least expensive Vintage Cars from ExotoDesigns. (1)
select productCode, productName, productLine, quantityinStock, MIN(buyPrice)
from Products
where productVendor = 'Exoto Designs'
AND productLine = 'Vintage Cars';
/*
select productCode, productName, productLine, quantityinStock, MIN(buyPrice)
from Products
where buyPrice = (select min(buyPrice)
from products
where productVendor = "Exoto Designs" and productLine = "Vintage Cars");
*/
#5. List the top 5 most expensive Order Items (by total cost) listing the product name, the vendor, the quantity and the total cost for each ordered item. (5) HINT: total cost = (quantityOrdered * priceEach)
select productName, productVendor, orderNumber, quantityOrdered, priceEach, sum(priceEach * quantityOrdered) as 'Total Cost'
from OrderDetails O, Products P
#where does the join
where O.productCode = P.productCode
group by productName, productVendor, orderNumber, quantityOrdered, priceEach
order by 'Total Cost' desc
limit 5;
#6. List the customerNumber, customerName, phone, country, state, corresponding RepEmployee’s Number, and creditLimit for customers with a credit limit of more than 130,000. List them in order from lowest to highest creditLimit. (5)
select customerNumber, customerName, phone, country, state, salesRepEmployeeNumber, creditLimit
from Customers
where creditLimit > 130000;
#7. List the productCode, productName, and count of orders for the product with the most orders where the productVendor is Welly Diecast Productions. Make sure to title the column heading for the count of orders as “OrderCount”. (1)
select O.productCode, productName, count(quantityOrdered) AS 'OrderCount' #SQL doesn't know where quantityOrdered is from
from Products P, orderDetails O
where productVendor = 'Welly Diecast Productions'
and P.productCode = O.productCode
#the rule for a group by is that every column name that is not a group function
group by O.productCode, productName
order by count(quantityOrdered) desc
limit 2;
/*8. (use SUBQUERY)
List the name, city, state, country, credit limit, and total products ordered for the top 3 customers who ordered the most products. (3)
(hint: who has the highest total quantity in OrderProducts across all their orders?) (3) */
select C.customerName, C.city, C.state, C.country, C.creditLimit, sum(OD.quantityOrdered) as totalorders
from Customers C
join Orders O
on C.customerNumber = O.customerNumber
join OrderDetails OD
on O.orderNumber = OD.orderNumber
group by C.customerNumber
order by totalorders desc
limit 3;
/*9. List the OfficeCode, city, state, country of all the offices that are not in USA
and occupying the entire building (the office has no addressLine2 recorded).(2)*/
select officeCode, city, state, country
from Offices
where country != "USA"
and addressline2 is null;
#10. List the productName and productLine for all Vintage Cars made in the 1930s (productName contains the string “193...”). (12)
select productName, productLine
from Products
where productName like '193%'
and productLine = "Vintage Cars";
/* 11. Select the order number, required date, shipped date, date difference, and shipped month for orders
which were shipped less than 3 days before they were due (required date - shipping date < 3) for orders shipped in 2005 (10). */
select orderNumber, requiredDate, shippedDate, (requiredDate - shippedDate) as dateDif, month(shippedDate)
from Orders
where (requiredDate - shippedDate) < 3
and year(shippedDate) = 2005;
/*12. List the customerNumber, customerName, city, country, and count of their orders for all customers whose customer number is lower than 150.
List them in descending order from highest to least number of orders. Title the column heading for the count of orders “Orders”. (15) */
select C.customerNumber, C.customerName, C.city, C.country, O.Orders
from Customers C
join(select customerNumber, count(orderNumber) as Orders from Orders group by customerNumber order by Orders) as O
on C.customerNumber = O.customerNumber
where C.customerNumber < 150
order by Orders desc;
/*13. List the customerName and customerNumber for customers in Switzerland that have no orders. (2) */
select C.customerName, C.customerNumber
from Customers C
left join Orders O
on C.customerNumber = O.customerNumber
where country = "Switzerland"
and O.customerNumber is null;
/*14. Select the product lines with over 12,000 orders (3)
In other words, if you tally up all the orders for classic cars, ships, trains, planes, etc., which categories have over 12,000 orders? */
select P.productLine
from Products P
join OrderDetails O
on P.productCode = O.productCode
group by P.productLine
having (sum(O.quantityOrdered) > 12000);
/*15. Create a NEW table named “TopCustomers” with four columns: CustomerNumber (integer), ContactDate (DATE), OrderCount(integer),
and OrderTotal (a decimal number with 9 digits in total having two decimal places). None of these columns can be NULL.
Include a PRIMARY KEY constraint named “TopCustomer_PK” on CustomerNumber. (no answer set) */
create table TopCustomers
(CustomerNumber int not null,
ContactDate date not null,
OrderCount int not null,
OrderTotal decimal(9,2) not null,
constraint TopCustomer_PK
primary key(CustomerNumber));
/* 16. Populate the new table “TopCustomers” with the CustomerNumber, today’s date, total number of orders (quantity),
and the total value of all their orders (PriceEach * quantityOrdered) for those customers whose order total value is greater than $130,000. (inserted 16 rows, no answer set) */
insert into TopCustomers(CustomerNumber, ContactDate, OrderCount, OrderTotal)
select C.CustomerNumber, curdate(), sum(quantityOrdered), sum(priceEach * quantityOrdered) as Total
from Customers C, Orders O, OrderDetails OD
where (C.CustomerNumber = O.CustomerNumber and O.orderNumber = OD.orderNumber)
group by customerNumber
having Total > 130000;
/*17. List the customerNumber, contactDate, orderCount, and orderTotal with the top five highest order totals from “TopCustomers” in descending orderTotal amount. (5) */
select CustomerNumber, ContactDate, OrderCount, OrderTotal
from TopCustomers
order by OrderTotal desc
limit 5;
/*18. Add a new column to the TopCustomers table called CustomerRatings (integer) set to zero by default. (No answer set) */
alter table TopCustomers
add CustomerRatings int default 0;
/*19. Update the TopCustomers table, setting the CustomerRatings column to a random number from 0 to*/
SET SQL_SAFE_UPDATES = 0;
update TopCustomers
set CustomerRatings = floor(rand() * (10-0) + 0);
/*20. List the contents of the TopCustomers table in descending CustomerRatings sequence. (16)*/
select *
from TopCustomers
order by CustomerRatings desc;
drop table TopCustomers; | true |
503914631c5819ef97505b4b2102cbcadd393e45 | SQL | ev-stepanov/spring-boot | /src/main/resources/data.sql | UTF-8 | 3,179 | 2.984375 | 3 | [] | no_license | -- Справочник №1
INSERT INTO Doc_type (id, version, doc_code, doc_name) VALUES (1, 0, 433, 'Passport');
INSERT INTO Doc_type (id, version, doc_code, doc_name) VALUES (2, 0, 24, 'Military ID');
-- Справочник №2
INSERT INTO Country (id, version, citizenship_code, citizenship_name) VALUES (1, 0, 64, 'USA');
INSERT INTO Country (id, version, citizenship_code, citizenship_name) VALUES (2, 0, 77, 'Japan');
-- Организация №1
INSERT INTO Organization (id, version, name, full_name, inn, kpp, address, phone, is_active)
VALUES (1, 0, 'Microsoft', 'Microsoft Corporation', '6449013711', '644901001', 'USA', '12121234567', true);
-- Офис №1
INSERT INTO Office (id, version, org_id, name, address, phone, is_active)
VALUES (1, 0, 1, 'Microsoft Washington', 'Washington 12', '12126458365', true);
--Документ работника №1
INSERT INTO Doc_user(id, version, doc_id, doc_date, doc_number)
VALUES (1, 0, 1, '2015-09-28', '404426');
-- Работник №1
INSERT INTO User (id, version, office_id, first_name, second_name, middle_name, doc_user_id,
citizenship_id, position, phone, is_identified)
VALUES (1, 0, 1, 'Ivan', 'Ivanov', 'Ivanovich', 1, 1, 'Manager', '12125463456', true);
-- Офис №2
INSERT INTO Office (id, version, org_id, name, address, phone, is_active)
VALUES (2, 0, 1, 'Microsoft New York', 'New York 34', '12127265432', true);
--Документ работника №2
INSERT INTO Doc_user(id, version, doc_id, doc_date, doc_number)
VALUES (2, 0, 1, '2016-07-18', '434141');
-- Работник №2
INSERT INTO User (id, version, office_id, first_name, second_name, middle_name, doc_user_id,
citizenship_id, position, phone, is_identified)
VALUES (2, 0, 2, 'Max', 'Smirnov', 'Alekseevich', 2, 2, 'Consultant', '12125463456', true);
-- Организация №2
INSERT INTO Organization (id, version, name, full_name, inn, kpp, address, phone, is_active)
VALUES (2, 0, 'Sony', 'Sony Corporation', '7722679627', '772201001', 'Japan', '31234567', false);
-- Офис №3
INSERT INTO Office (id, version, org_id, name, address, phone, is_active)
VALUES (3, 0, 2, 'Sony Tokio', 'Tokio 112', '3127354', true);
--Документ работника №3
INSERT INTO Doc_user(id, version, doc_id, doc_date, doc_number)
VALUES (3, 0, 2, '2013-11-14', '394426');
-- Работник №3
INSERT INTO User (id, version, office_id, first_name, second_name, middle_name, doc_user_id,
citizenship_id, position, phone)
VALUES (3, 0, 3, 'Anastasia', 'Titova', 'Vassilievna', 3, 1, 'Java Developer', '3127355');
-- Офис №4
INSERT INTO Office (id, version, org_id, name, address, phone, is_active)
VALUES (4, 0, 2, 'Sony New York', 'New York 36', '12126458365', false);
--Документ работника №4
INSERT INTO Doc_user(id, version, doc_id, doc_date, doc_number)
VALUES (4, 0, 2, '2013-12-28', '414356');
-- Работник №4
INSERT INTO User (id, version, office_id, first_name, second_name, doc_user_id,
citizenship_id, position, phone)
VALUES (4, 0, 3, 'Aleksandr', 'Kafidov', 4, 2, 'UI', '12126458367'); | true |
336ff0d5fb7fb5e0de3b38472b5cd401a0717763 | SQL | medy13/dbshell | /normal_shell/RED_LIST.sql | UTF-8 | 1,087 | 2.75 | 3 | [] | no_license | \echo ------------------RED_LIST----------------
select now();
\timing
insert into RED_LIST_GPTMP (CMD_TYPE,CUT_ID, MODIFY_TIMES, G_NO) select CMD_TYPE,CUT_ID, MODIFY_TIMES, G_NO from RED_LIST_INC_EXT;
delete from RED_LIST using RED_LIST_GPTMP where RED_LIST_GPTMP.CUT_ID=RED_LIST.CUT_ID AND RED_LIST_GPTMP.MODIFY_TIMES=RED_LIST.MODIFY_TIMES AND RED_LIST_GPTMP.G_NO=RED_LIST.G_NO ;
insert into RED_LIST(CUT_ID,MODIFY_TIMES,G_NO,MAN_G_NO,CODE_TS,CLASS_MARK,G_NAME,G_MODEL,ORIGIN_COUNTRY,G_UNIT,G_QTY,UNIT_1,QTY_1,UNIT_2,QTY_2,DECL_TOTAL,TRADE_CURR,DUTY_MODE,D_RATE,T_RATE,O_RATE,DUTY_RATE,TAX_RATE,OTHER_RATE,DUTY_CUT,TAX_CUT,OTHER_CUT,APPR_QUOTA,FACT_AMT,FACT_QTY,DUTY_VALUE,AUDIT_FLAG,RESERVE1,NOTE) select CUT_ID,MODIFY_TIMES,G_NO,MAN_G_NO,CODE_TS,CLASS_MARK,G_NAME,G_MODEL,ORIGIN_COUNTRY,G_UNIT,G_QTY,UNIT_1,QTY_1,UNIT_2,QTY_2,DECL_TOTAL,TRADE_CURR,DUTY_MODE,D_RATE,T_RATE,O_RATE,DUTY_RATE,TAX_RATE,OTHER_RATE,DUTY_CUT,TAX_CUT,OTHER_CUT,APPR_QUOTA,FACT_AMT,FACT_QTY,DUTY_VALUE,AUDIT_FLAG,RESERVE1,NOTE from RED_LIST_INC_EXT where CMD_TYPE='I';
delete from RED_LIST_GPTMP;
\timing
| true |
420ec6954f191d58e0871f934bec40f781dc8fe8 | SQL | Symplicity/subdivision-list | /data/en/postgres/subdivisions_SS.postgres.sql | UTF-8 | 1,127 | 2.6875 | 3 | [
"MIT"
] | permissive | CREATE TABLE subdivision_SS (id VARCHAR(6) NOT NULL, name VARCHAR(255), level VARCHAR(64) NOT NULL, PRIMARY KEY(id));
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-EC', E'Central Equatoria', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-EE', E'Eastern Equatoria', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-JG', E'Jonglei', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-LK', E'Lake', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-BN', E'Northern Bahr el Ghazal', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-UY', E'Unity', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-NU', E'Upper Nile', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-WR', E'Warrap', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-BW', E'Western Bahr el Ghazal', E'states');
INSERT INTO "subdivision_SS" ("id", "name", "level") VALUES (E'SS-EW', E'Western Equatoria', E'states');
| true |
a25f8fb0645d88342f079255c57059c670404a93 | SQL | diazadha/Basis-Data-Lanjut | /mstore/marketplace (1).sql | UTF-8 | 21,821 | 2.984375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.9.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Waktu pembuatan: 02 Apr 2020 pada 13.12
-- Versi server: 10.4.8-MariaDB
-- Versi PHP: 7.1.33
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `marketplace`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `admintoko`
--
CREATE TABLE `admintoko` (
`id_admin` int(11) NOT NULL,
`name` varchar(128) NOT NULL,
`email` varchar(128) NOT NULL,
`image` text NOT NULL,
`password` varchar(128) NOT NULL,
`id_role` int(11) NOT NULL,
`is_active` int(1) NOT NULL,
`date_created` varchar(30) NOT NULL,
`alamat_admin` varchar(256) NOT NULL,
`kodepos` int(10) NOT NULL,
`kota_admin` varchar(256) NOT NULL,
`kontak_admin` varchar(13) NOT NULL,
`id_toko` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `admintoko`
--
INSERT INTO `admintoko` (`id_admin`, `name`, `email`, `image`, `password`, `id_role`, `is_active`, `date_created`, `alamat_admin`, `kodepos`, `kota_admin`, `kontak_admin`, `id_toko`) VALUES
(1, 'Indo', 'dani.book@yahoo.com', 'default.jpg', '$2y$10$bms4Otkvh78K1a7SVgdjHO/AekCQ9DUVGEnN1xahPoOWbG8fTNUAC', 2, 1, '1585452346', '', 0, '', '', 2);
-- --------------------------------------------------------
--
-- Struktur dari tabel `armada`
--
CREATE TABLE `armada` (
`id` int(11) NOT NULL,
`layanan` varchar(10) NOT NULL,
`harga_layanan` int(128) NOT NULL,
`nama_armada` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `armada`
--
INSERT INTO `armada` (`id`, `layanan`, `harga_layanan`, `nama_armada`) VALUES
(1, 'jn', 12312, 'asdasdf'),
(2, 'jntw', 12312, 'asdasdf'),
(3, 'jntw', 12312, 'asdasdf'),
(4, 'jntwasdfa', 12312124, 'asdasdfad'),
(5, 'jntwasdfa', 12312124, 'asdasdfad'),
(6, 'jntwasdfa', 12312124, 'asdasdfad');
-- --------------------------------------------------------
--
-- Struktur dari tabel `barang`
--
CREATE TABLE `barang` (
`id_barang` int(11) NOT NULL,
`nama_barang` varchar(128) NOT NULL,
`harga_barang` int(128) NOT NULL,
`stok_barang` int(30) NOT NULL,
`foto_barang` text NOT NULL,
`deskripsi_barang` text NOT NULL,
`keterangan` varchar(255) NOT NULL,
`diskon` int(11) NOT NULL,
`id_toko` int(11) NOT NULL,
`id_kategori` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `barang`
--
INSERT INTO `barang` (`id_barang`, `nama_barang`, `harga_barang`, `stok_barang`, `foto_barang`, `deskripsi_barang`, `keterangan`, `diskon`, `id_toko`, `id_kategori`) VALUES
(1, 'Jaket Bomber', 5, 50, 'barang.jpg', '<p>Material Scoot Waterproof / Anti Air Bahan dalam Dakron tebal Terdapat 1 kantong di bagian dalam dan 2 kantong</p>\r\n\r\n<p>di bagian luar Jahitan Rapih dan kuat</p>\r\n\r\n<p><strong>Warna:</strong></p>\r\n\r\n<ol>\r\n <li>Hitam,</li>\r\n <li>Navy,</li>\r\n <li>Marun,&</li>\r\n</ol>\r\n\r\n<p><strong>Warna:</strong></p>\r\n\r\n<ol>\r\n <li>Hitam,</li>\r\n <li>Navy,</li>\r\n <li>Marun,&</li>\r\n <li>\r\n <p><strong>Warna:</strong></p>\r\n </li>\r\n <li>Hitam,</li>\r\n <li>Navy,</li>\r\n <li>Marun,&</li>\r\n</ol>\r\n\r\n<p> </p>\r\n\r\n<p><strong>Warna:</strong></p>\r\n\r\n<ol>\r\n <li>Hitam,</li>\r\n <li>Navy,</li>\r\n <li>Marun,&</li>\r\n</ol>\r\n', 'Ini adalah keterangan singkat Ini adalah keterangan singkat Ini adalah keterangan singkat ', 0, 1, 1),
(7, 'Coba', 12, 23, 'download_(1)2.jpg', '<p>asdfa</p>\r\n', 'sdfasdf', 3, 1, 1),
(9, 'Jaket Bomber Polos Pria m', 678888, 12, 'download_(1)3.jpg', '<p>asdcad</p>\r\n', ' mnmn', 3, 1, 1),
(10, 'Coba 12314', 2323436, 78, 'hp.jpg', '<p>adsgasd</p>\r\n', 'adf', 12, 1, 1),
(16, 'Jaket Bomber Polos Pria ', 76576, 23, 'hp1.jpg', '<p>dvsdva</p>\r\n', 'dsdca', 3, 1, 0),
(17, 'asadfa', 76576, 78, 'download_(1)6.jpg', '<p>sadfasd</p>\r\n', 'adfad', 12, 1, 0),
(18, 'Coba 12314', 76576, 12, 'beras8.JPG', '<p>asdcasdcasdcasdc</p>\r\n', 'asdca', 12, 1, 0),
(19, 'qq', 100000, 123, 'download6.jpg', '<p>qsas</p>\r\n', 'qw', 20, 1, 8),
(21, 'Coba', 678888, 78, 'download_(1)7.jpg', '<p>asfasdva</p>\r\n', 'asdakjsdn', 12, 1, 0),
(22, 'Jaket Bomber Polos ', 678888, 3, '3.jpg', '<p>zxcvzxcv</p>\r\n', 'zxvcz', 3, 1, 0),
(23, 'Jaket fe ', 76576, 78, '2.png', '<p>vasdvasd</p>\r\n', 'asdca', 23, 2, 0);
-- --------------------------------------------------------
--
-- Struktur dari tabel `discountcodes`
--
CREATE TABLE `discountcodes` (
`id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`code` varchar(30) NOT NULL,
`startdate` datetime NOT NULL,
`enddate` datetime NOT NULL,
`discount` int(11) NOT NULL,
`percent` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Struktur dari tabel `diskon`
--
CREATE TABLE `diskon` (
`id` int(11) NOT NULL,
`id_barang` int(120) NOT NULL,
`min_qty` int(11) NOT NULL,
`potongan` int(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Struktur dari tabel `invoice`
--
CREATE TABLE `invoice` (
`id` int(11) NOT NULL,
`nama_pemesan` varchar(128) NOT NULL,
`hp_pemesan` varchar(13) NOT NULL,
`kota_pemesan` varchar(128) NOT NULL,
`kodepos` varchar(8) NOT NULL,
`alamat` text NOT NULL,
`order_date` datetime NOT NULL,
`batas_bayar` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `invoice`
--
INSERT INTO `invoice` (`id`, `nama_pemesan`, `hp_pemesan`, `kota_pemesan`, `kodepos`, `alamat`, `order_date`, `batas_bayar`) VALUES
(3, 'makmudin', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 19:58:23', '2019-12-01 19:58:23'),
(4, 'makmudin', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 20:11:48', '2019-12-01 20:11:48'),
(5, 'makmudin', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 20:12:03', '2019-12-01 20:12:03'),
(6, 'makmudin', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 20:17:38', '2019-12-01 20:17:38'),
(7, 'makmudin', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 20:18:37', '2019-12-01 20:18:37'),
(8, 'makmudin', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 20:20:19', '2019-12-01 20:20:19'),
(9, 'makmudin', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 20:20:28', '2019-12-01 20:20:28'),
(10, 'makmudin', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 20:27:09', '2020-04-02 20:27:09'),
(11, 'makmudin coba', '089672231770', 'Jakarta Selatan', '12110', 'Jl. Sisingamangaraja, Kebayoran Baru', '2020-04-01 21:03:34', '2020-04-02 21:03:34');
-- --------------------------------------------------------
--
-- Struktur dari tabel `isi_keranjang`
--
CREATE TABLE `isi_keranjang` (
`id_isi_keranjang` int(11) NOT NULL,
`id_invoice` int(11) NOT NULL,
`id_barang` int(11) NOT NULL,
`jumlah_barang` int(30) NOT NULL,
`harga_barang` int(30) NOT NULL,
`total_harga` int(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Struktur dari tabel `kategori`
--
CREATE TABLE `kategori` (
`id_kategori` int(11) NOT NULL,
`nama_kategori` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `kategori`
--
INSERT INTO `kategori` (`id_kategori`, `nama_kategori`) VALUES
(1, 'Fashion Pria'),
(2, 'Fashion Wanita'),
(8, 'cobas'),
(9, 'Dapur');
-- --------------------------------------------------------
--
-- Struktur dari tabel `orders`
--
CREATE TABLE `orders` (
`id` int(11) NOT NULL,
`id_invoice` int(11) NOT NULL,
`id_barang` int(11) NOT NULL,
`nama_barang` varchar(30) NOT NULL,
`jumlah` int(11) NOT NULL,
`harga` int(30) NOT NULL,
`pilihan` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `orders`
--
INSERT INTO `orders` (`id`, `id_invoice`, `id_barang`, `nama_barang`, `jumlah`, `harga`, `pilihan`) VALUES
(1, 6, 10, 'Coba 12314', 1, 2323436, ''),
(2, 11, 1, 'Jaket Bomber', 1, 4500, ''),
(3, 11, 7, 'Coba', 1, 12, ''),
(4, 11, 9, 'Jaket Bomber Polos Pria m', 1, 678888, ''),
(5, 11, 10, 'Coba 12314', 1, 2323436, '');
-- --------------------------------------------------------
--
-- Struktur dari tabel `pembayaran`
--
CREATE TABLE `pembayaran` (
`id` int(11) NOT NULL,
`id_invoice` int(11) NOT NULL,
`metode_bayar` varchar(255) NOT NULL,
`mitra_bayar` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `pembayaran`
--
INSERT INTO `pembayaran` (`id`, `id_invoice`, `metode_bayar`, `mitra_bayar`) VALUES
(8, 0, 'Transfer', 'bcacc');
-- --------------------------------------------------------
--
-- Struktur dari tabel `pembeli`
--
CREATE TABLE `pembeli` (
`id` int(11) NOT NULL,
`nama_penerima` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`kontak` varchar(50) NOT NULL,
`alamat` varchar(200) NOT NULL,
`kode_pos` varchar(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Struktur dari tabel `stock_barang`
--
CREATE TABLE `stock_barang` (
`id` int(30) NOT NULL,
`id_barang` int(120) NOT NULL,
`qty` int(11) NOT NULL,
`type` enum('in','out') NOT NULL,
`detail` text NOT NULL,
`date` date NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Struktur dari tabel `tarif`
--
CREATE TABLE `tarif` (
`id_tarif` int(11) NOT NULL,
`alamat_tujuan` varchar(128) NOT NULL,
`harga_tarif` int(128) NOT NULL,
`id_armada` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Struktur dari tabel `toko`
--
CREATE TABLE `toko` (
`id` int(11) NOT NULL,
`nama_toko` varchar(128) NOT NULL,
`alamat_toko` varchar(128) NOT NULL,
`kodepos_toko` int(30) NOT NULL,
`foto_toko` text NOT NULL,
`kota_toko` varchar(128) NOT NULL,
`kontak_toko` varchar(13) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `toko`
--
INSERT INTO `toko` (`id`, `nama_toko`, `alamat_toko`, `kodepos_toko`, `foto_toko`, `kota_toko`, `kontak_toko`) VALUES
(1, 'MSTORE CINERE', 'Jl. Cinere Raya', 16513, 'toko.jpg', 'Depok', '089672231770'),
(2, 'Indo Store', 'Jl. Sisingamangaraja, Kebayoran Baru', 12110, 'store.jpg', 'Jakarta Selatan', '089672231770');
-- --------------------------------------------------------
--
-- Struktur dari tabel `user`
--
CREATE TABLE `user` (
`id_user` int(10) NOT NULL,
`name` varchar(128) NOT NULL,
`email` varchar(128) NOT NULL,
`image` text NOT NULL,
`password` varchar(256) NOT NULL,
`id_role` int(10) NOT NULL,
`is_active` int(1) NOT NULL,
`date_created` varchar(30) NOT NULL DEFAULT current_timestamp(),
`alamat_user` varchar(256) NOT NULL,
`kodepos` int(10) NOT NULL,
`kota_user` varchar(256) NOT NULL,
`kontak_user` varchar(13) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `user`
--
INSERT INTO `user` (`id_user`, `name`, `email`, `image`, `password`, `id_role`, `is_active`, `date_created`, `alamat_user`, `kodepos`, `kota_user`, `kontak_user`) VALUES
(1, 'Makmudin', 'id.makmudin@gmail.com', 'default.jpg', '$2y$10$qW3vhlDMYHHH6eYq4ppXNe4bvjxBIcLfdEo/9qVh4/EOo/iLeArMK', 2, 1, '1579999999', '', 0, '', ''),
(2, 'Diaz', 'diaz.adha@if.uai.ac.id', 'default.jpg', '$2y$10$Bc9nogEHI8fr7P7n0vaY9eedjdmbdHU7lK7P7IOyJGtFPbtaWcfJq', 1, 1, '1584386234', '', 0, '', ''),
(5, 'Admin Toko', 'makmudin.uai@gmail.com', 'default.jpg', '$2y$10$P5UHnRliOOO6mPpNRiW0V.Ji3b0s8A745ti/WunpJbFj74mBalchG', 2, 1, '1584690975', '', 0, '', '');
-- --------------------------------------------------------
--
-- Struktur dari tabel `user_access_menu`
--
CREATE TABLE `user_access_menu` (
`id_access_menu` int(11) NOT NULL,
`id_role` int(11) NOT NULL,
`id_menu` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `user_access_menu`
--
INSERT INTO `user_access_menu` (`id_access_menu`, `id_role`, `id_menu`) VALUES
(1, 1, 1),
(3, 2, 2),
(4, 1, 3),
(7, 1, 5),
(8, 1, 16),
(9, 1, 17),
(10, 1, 19),
(12, 2, 26),
(14, 2, 21),
(15, 2, 4),
(16, 2, 22),
(17, 2, 23),
(18, 2, 24),
(19, 2, 32),
(20, 2, 25);
-- --------------------------------------------------------
--
-- Struktur dari tabel `user_menu`
--
CREATE TABLE `user_menu` (
`id` int(11) NOT NULL,
`menu` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `user_menu`
--
INSERT INTO `user_menu` (`id`, `menu`) VALUES
(1, 'Admin'),
(2, 'User'),
(3, 'Menu'),
(4, 'Manage Store'),
(22, 'Manage Payment'),
(23, 'Manage Courier'),
(24, 'Admin Store'),
(25, 'Manage Transaction');
-- --------------------------------------------------------
--
-- Struktur dari tabel `user_role`
--
CREATE TABLE `user_role` (
`id` int(11) NOT NULL,
`role` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `user_role`
--
INSERT INTO `user_role` (`id`, `role`) VALUES
(1, 'Administrator Market Toko'),
(2, 'Admin Toko');
-- --------------------------------------------------------
--
-- Struktur dari tabel `user_sub_menu`
--
CREATE TABLE `user_sub_menu` (
`id_sub_menu` int(11) NOT NULL,
`id_menu` int(11) NOT NULL,
`title` varchar(128) NOT NULL,
`url` varchar(128) NOT NULL,
`icon` varchar(128) NOT NULL,
`is_active` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `user_sub_menu`
--
INSERT INTO `user_sub_menu` (`id_sub_menu`, `id_menu`, `title`, `url`, `icon`, `is_active`) VALUES
(8, 1, 'Dashboard', 'dashboard_marketplace/index', 'fas fa-fw fa-tachometer-alt', 1),
(9, 2, 'My Profile', 'profil_toko/index', 'fas fa-fw fa-user', 1),
(10, 2, 'Edit Profile', 'profile/edit', 'fas fa-fw fa-user-edit', 1),
(11, 3, 'Menu Management', 'menu', 'fas fa-fw fa-folder', 1),
(12, 3, 'Sub Menu Management', 'menu/submenu', 'far fa-fw fa-folder-open', 1),
(19, 4, 'Data Barang', 'toko/databarang', 'fas fa-fw fa-list', 1),
(20, 14, 'TOKO IF Cinere', 'toko/cabang', 'fas fa-fw fa-store', 1),
(23, 18, 'Data Barang', 'toko/databarang', 'fas fa-fw fa-store', 1),
(24, 16, 'asdvan', 'databarang', 'fas fa-fw fa-store', 1),
(25, 19, 'List Store', 'store', 'fas fa-fw fa-list', 1),
(26, 4, 'Kategori Barang', 'toko/kategoribarang', 'fas fa-fw fa-list', 1),
(27, 21, 'My Store', 'toko/store', 'fas fa-fw fa-store', 1),
(28, 22, 'Payment Method', 'toko/payment', 'fas fa-fw fa-money-bill-wave', 1),
(29, 23, 'Courier', 'toko/kurir', 'fas fa-fw fa-truck', 1),
(30, 24, 'Dashboard', 'dashboard_toko', ' fas fa-fw fa-tachometer-alt ', 1),
(31, 4, 'Diskon Barang', 'toko/diskonbarang', 'far fa-fw fa-tags', 1),
(32, 4, 'Stock In Product', 'stock/in/', 'fas fa-fw fa-inventory', 1),
(33, 25, 'Data Pesanan', 'toko/invoice', 'fas fa-luggage-cart', 1);
--
-- Indexes for dumped tables
--
--
-- Indeks untuk tabel `admintoko`
--
ALTER TABLE `admintoko`
ADD PRIMARY KEY (`id_admin`),
ADD KEY `id_role` (`id_role`,`id_toko`);
--
-- Indeks untuk tabel `armada`
--
ALTER TABLE `armada`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `barang`
--
ALTER TABLE `barang`
ADD PRIMARY KEY (`id_barang`),
ADD KEY `id_toko` (`id_toko`),
ADD KEY `id_kategori` (`id_kategori`);
--
-- Indeks untuk tabel `discountcodes`
--
ALTER TABLE `discountcodes`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `diskon`
--
ALTER TABLE `diskon`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `invoice`
--
ALTER TABLE `invoice`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `isi_keranjang`
--
ALTER TABLE `isi_keranjang`
ADD PRIMARY KEY (`id_isi_keranjang`),
ADD KEY `id_invoice` (`id_invoice`),
ADD KEY `id_barang` (`id_barang`);
--
-- Indeks untuk tabel `kategori`
--
ALTER TABLE `kategori`
ADD PRIMARY KEY (`id_kategori`);
--
-- Indeks untuk tabel `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `pembayaran`
--
ALTER TABLE `pembayaran`
ADD PRIMARY KEY (`id`),
ADD KEY `id_invoice` (`id_invoice`),
ADD KEY `id_invoice_2` (`id_invoice`);
--
-- Indeks untuk tabel `pembeli`
--
ALTER TABLE `pembeli`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `stock_barang`
--
ALTER TABLE `stock_barang`
ADD PRIMARY KEY (`id`),
ADD KEY `id_barang` (`id_barang`);
--
-- Indeks untuk tabel `tarif`
--
ALTER TABLE `tarif`
ADD PRIMARY KEY (`id_tarif`),
ADD KEY `id_armada` (`id_armada`);
--
-- Indeks untuk tabel `toko`
--
ALTER TABLE `toko`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id_user`),
ADD KEY `id_role` (`id_role`);
--
-- Indeks untuk tabel `user_access_menu`
--
ALTER TABLE `user_access_menu`
ADD PRIMARY KEY (`id_access_menu`),
ADD KEY `id_role` (`id_role`),
ADD KEY `id_menu` (`id_menu`);
--
-- Indeks untuk tabel `user_menu`
--
ALTER TABLE `user_menu`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `user_role`
--
ALTER TABLE `user_role`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `user_sub_menu`
--
ALTER TABLE `user_sub_menu`
ADD PRIMARY KEY (`id_sub_menu`),
ADD KEY `id_menu` (`id_menu`);
--
-- AUTO_INCREMENT untuk tabel yang dibuang
--
--
-- AUTO_INCREMENT untuk tabel `admintoko`
--
ALTER TABLE `admintoko`
MODIFY `id_admin` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT untuk tabel `armada`
--
ALTER TABLE `armada`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT untuk tabel `barang`
--
ALTER TABLE `barang`
MODIFY `id_barang` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;
--
-- AUTO_INCREMENT untuk tabel `discountcodes`
--
ALTER TABLE `discountcodes`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT untuk tabel `diskon`
--
ALTER TABLE `diskon`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT untuk tabel `invoice`
--
ALTER TABLE `invoice`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT untuk tabel `isi_keranjang`
--
ALTER TABLE `isi_keranjang`
MODIFY `id_isi_keranjang` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT untuk tabel `kategori`
--
ALTER TABLE `kategori`
MODIFY `id_kategori` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT untuk tabel `orders`
--
ALTER TABLE `orders`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT untuk tabel `pembayaran`
--
ALTER TABLE `pembayaran`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT untuk tabel `pembeli`
--
ALTER TABLE `pembeli`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT untuk tabel `stock_barang`
--
ALTER TABLE `stock_barang`
MODIFY `id` int(30) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT untuk tabel `tarif`
--
ALTER TABLE `tarif`
MODIFY `id_tarif` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT untuk tabel `toko`
--
ALTER TABLE `toko`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT untuk tabel `user`
--
ALTER TABLE `user`
MODIFY `id_user` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT untuk tabel `user_access_menu`
--
ALTER TABLE `user_access_menu`
MODIFY `id_access_menu` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT untuk tabel `user_menu`
--
ALTER TABLE `user_menu`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26;
--
-- AUTO_INCREMENT untuk tabel `user_role`
--
ALTER TABLE `user_role`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT untuk tabel `user_sub_menu`
--
ALTER TABLE `user_sub_menu`
MODIFY `id_sub_menu` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34;
--
-- Ketidakleluasaan untuk tabel pelimpahan (Dumped Tables)
--
--
-- Ketidakleluasaan untuk tabel `barang`
--
ALTER TABLE `barang`
ADD CONSTRAINT `barang_ibfk_1` FOREIGN KEY (`id_toko`) REFERENCES `toko` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ketidakleluasaan untuk tabel `isi_keranjang`
--
ALTER TABLE `isi_keranjang`
ADD CONSTRAINT `isi_keranjang_ibfk_1` FOREIGN KEY (`id_invoice`) REFERENCES `invoice` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `isi_keranjang_ibfk_2` FOREIGN KEY (`id_barang`) REFERENCES `barang` (`id_barang`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ketidakleluasaan untuk tabel `stock_barang`
--
ALTER TABLE `stock_barang`
ADD CONSTRAINT `stock_barang_ibfk_1` FOREIGN KEY (`id_barang`) REFERENCES `barang` (`id_barang`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ketidakleluasaan untuk tabel `tarif`
--
ALTER TABLE `tarif`
ADD CONSTRAINT `tarif_ibfk_1` FOREIGN KEY (`id_armada`) REFERENCES `armada` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ketidakleluasaan untuk tabel `user`
--
ALTER TABLE `user`
ADD CONSTRAINT `user_ibfk_1` FOREIGN KEY (`id_role`) REFERENCES `user_role` (`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 |
fce060cc56097ef0b605b63c9675912a41aa2b02 | SQL | akellan/thaitrip-gatsby | /wp-data/sql/terms.sql | UTF-8 | 190 | 3.046875 | 3 | [
"MIT"
] | permissive | SELECT * FROM wp_term_relationships tr INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN wp_terms t ON t.term_id = tt.term_id where taxonomy = 'post_tag' | true |
7bd70d7a41cf6f215e5d18f4a8d192d56f5e9065 | SQL | cbeard22/trackMyEmployee | /schema.sql | UTF-8 | 1,296 | 3.875 | 4 | [
"MIT"
] | permissive | DROP DATABASE IF EXISTS employee_trackerDB;
CREATE DATABASE employee_trackerDB;
USE employee_trackerDB;
CREATE TABLE department (
id INT AUTO_INCREMENT NOT NULL,
name VARCHAR(30),
PRIMARY KEY (id)
);
CREATE TABLE role (
id INT AUTO_INCREMENT NOT NULL ,
title VARCHAR(30),
salary DECIMAL(10,2),
department_id INT,
PRIMARY KEY(id),
FOREIGN KEY (department_id) REFERENCES department(id) ON DELETE CASCADE
);
CREATE TABLE employee (
id INT AUTO_INCREMENT NOT NULL,
first_name VARCHAR(30),
last_name VARCHAR(30),
role_id INT,
manager_id INT,
FOREIGN KEY (role_id) REFERENCES role(id) ON DELETE CASCADE,
FOREIGN KEY (manager_id) REFERENCES employee(id) ON DELETE CASCADE,
PRIMARY KEY(id)
);
-- SEEDS
INSERT INTO department (name)
VALUE ("Sales");
INSERT INTO department (name)
VALUE ("Management");
INSERT INTO role (title, salary, department_id)
VALUE ("Employee", 80000, 1);
INSERT INTO role (title, salary, department_id)
VALUE ("Manager", 250000, 2);
INSERT INTO employee (first_name, last_name, manager_id, role_id)
VALUE ("Billy", "Bob", 1, NULL);
INSERT INTO employee (first_name, last_name, manager_id, role_id)
VALUE ("Courtney", "Hertig", 2, 1);
SELECT * FROM department;
SELECT * FROM role;
SELECT * FROM employee;
| true |
17742aa3d8426c5b4470258dc26553762acfbc04 | SQL | ViKtorMacias/ScriptsToolServer | /ParametrosSP.sql | UTF-8 | 520 | 3.609375 | 4 | [] | no_license |
SELECT SCHEMA_NAME(SCHEMA_ID) AS [Schema],
SO.name AS [ObjectName],
SO.Type_Desc AS [ObjectType (UDF/SP)],
P.parameter_id AS [ParameterID],
P.name AS [ParameterName],
TYPE_NAME(P.user_type_id) AS [ParameterDataType],
P.max_length AS [ParameterMaxBytes],
P.is_output AS [IsOutPutParameter]
FROM sys.objects AS SO
INNER JOIN sys.parameters AS P
ON SO.OBJECT_ID = P.OBJECT_ID
WHERE SO.OBJECT_ID IN ( SELECT OBJECT_ID
FROM sys.objects
WHERE TYPE IN ('P','FN'))
and SO.name =''
ORDER BY [Schema], SO.name, P.parameter_id
| true |
86bc851f68729a07f0b613e06c38af0c711e13bb | SQL | diegocarreto/SICAP | /DataBase/StoreProcedure/CatalogList.sql | UTF-8 | 154 | 3 | 3 | [] | no_license | CREATE PROC CatalogList
@type VARCHAR(50)
AS
SELECT
id,
name
FROM
[catalog]
WHERE
deleted = 0
AND [type] = @type
ORDER BY
name ASC | true |
680a3a6fccd2727348956d2280b46c6845dc281e | SQL | opengauss-mirror/openGauss-server | /src/test/regress/sql/postgis_function_3.sql | UTF-8 | 31,875 | 3.125 | 3 | [
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference",
"PostgreSQL",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"curl",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"CC-BY-4.0",
... | permissive | set current_schema=postgis;
SELECT ST_GeometryType(geomA) As geomtype, ST_Contains(geomA,geomA) AS acontainsa,
ST_ContainsProperly(geomA, geomA) AS acontainspropa,
ST_Contains(geomA, ST_Boundary(geomA)) As acontainsba, ST_ContainsProperly(geomA,
ST_Boundary(geomA)) As acontainspropba
FROM (VALUES ( ST_Buffer(ST_Point(1,1), 5,1) ),
( ST_MakeLine(ST_Point(1,1), ST_Point(-1,-1) ) ),
( ST_Point(1,1) )
) As foo(geomA);
SELECT ST_3DPerimeter(the_geom), ST_Perimeter2d(the_geom), ST_Perimeter(the_geom) FROM
(SELECT ST_GeomFromEWKT('SRID=2249;POLYGON((743238 2967416 2,743238 2967450 1,
743265.625 2967416 1,743238 2967416 2))') As the_geom) As foo;
SELECT ST_Contains(smallc, bigc) As smallcontainsbig,
ST_Contains(bigc,smallc) As bigcontainssmall,
ST_Contains(bigc, ST_Union(smallc, bigc)) as bigcontainsunion,
ST_Equals(bigc, ST_Union(smallc, bigc)) as bigisunion,
ST_Covers(bigc, ST_ExteriorRing(bigc)) As bigcoversexterior,
ST_Contains(bigc, ST_ExteriorRing(bigc)) As bigcontainsexterior
FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc,
ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo;
SELECT ST_GeometryType(geomA) As geomtype, ST_Contains(geomA,geomA) AS acontainsa,
ST_ContainsProperly(geomA, geomA) AS acontainspropa,
ST_Contains(geomA, ST_Boundary(geomA)) As acontainsba, ST_ContainsProperly(geomA,
ST_Boundary(geomA)) As acontainspropba
FROM (VALUES ( ST_Buffer(ST_Point(1,1), 5,1) ),
( ST_MakeLine(ST_Point(1,1), ST_Point(-1,-1) ) ),
( ST_Point(1,1) )
) As foo(geomA);
SELECT ST_GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27
29.31,77.29 29.07)'));
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0
0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )'));
SELECT ST_IsSimple(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))'));
SELECT ST_IsSimple(ST_GeomFromText('LINESTRING(1 1,2 2,2 3.5,1 3,1 2,2 1)'));
SELECT tbl1.column1, tbl2.column1, tbl1.column2 >> tbl2.column2 AS right
FROM
( VALUES
(1, 'LINESTRING (2 3, 5 6)'::geometry)) AS tbl1,
( VALUES
(2, 'LINESTRING (1 4, 1 7)'::geometry),
(3, 'LINESTRING (6 1, 6 5)'::geometry),
(4, 'LINESTRING (0 0, 4 3)'::geometry)) AS tbl2;
SELECT ST_asewkt(ST_removepoint('LINESTRING(0 0 0 0, 1 1 1 1, 2 2 2 2)', 0));
SELECT ST_asewkt(ST_removepoint('LINESTRING(0 0 0 0, 1 1 1 1, 2 2 2 2)', 2));
SELECT ST_RemovePoint('POINT(-11.1111111 40)'::geometry, 1);
SELECT ST_AsEWKT(
ST_GeomFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@',4326)
);
SELECT
ST_AsText(
ST_GeomFromWKB(
ST_AsEWKB('POINT(2 5)'::geometry)
)
);
SELECT 8, ST_AsText(ST_RemoveRepeatedPoints('POINT(0 0)'));
SELECT 10, ST_AsText(ST_RemoveRepeatedPoints('LINESTRING(0 0, 0 0)'));
SELECT 11, ST_AsText(ST_RemoveRepeatedPoints('LINESTRING(0 0, 0 0, 0 0, 0 0, 0 0)'));
SELECT 12, ST_SRID(ST_RemoveRepeatedPoints('SRID=3;LINESTRING(0 0, 0 0, 0 0, 0 0, 0 0)'));
SELECT 13, ST_AsText(ST_RemoveRepeatedPoints('LINESTRING(0 0, 1 0, 2 0, 3 0, 4 0)',1.5));
SELECT 14, ST_AsText(ST_RemoveRepeatedPoints('LINESTRING(10 0,10 9,10 10)', 2));
SELECT 15, ST_AsText(ST_RemoveRepeatedPoints('MULTIPOINT(0 0, 0 0, 1 1, 2 2)'::geometry));
SELECT 16, ST_AsText(ST_RemoveRepeatedPoints('MULTIPOINT(0 0, 0 0, 1 1, 2 2)'::geometry,0.1));
SELECT 17, ST_AsText(ST_RemoveRepeatedPoints('MULTIPOINT(0 0, 0 0, 1 1, 4 4)'::geometry,2));
SELECT ST_NPoints(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29
29.07)'));
SELECT ST_NPoints(ST_GeomFromEWKT('LINESTRING(77.29 29.07 1,77.42 29.26 0,77.27 29.31
-1,77.29 29.07 3)'));
SELECT ST_AsEWKT(ST_AddPoint(ST_GeomFromEWKT('LINESTRING(0 0 1, 1 1 1)'), ST_MakePoint
(1, 2, 3)));
SELECT CAST(ST_Expand(ST_GeomFromText('LINESTRING(2312980 110676,2312923 110701,2312892
110714)', 2163),10) As box2d);
SELECT ST_Expand(CAST('BOX3D(778783 2951741 1,794875 2970042.61545891 10)' As box3d),10);
SELECT ST_AsEWKT(ST_Expand(ST_GeomFromEWKT('SRID=2163;POINT(2312980 110676)'),10));
SELECT ST_AsText(the_geom)
FROM
(SELECT ST_LocateBetween(
ST_GeomFromText('MULTILINESTRING M ((1 2 3, 3 4 2, 9 4 3),
(1 2 3, 5 4 5))'),1.5, 3) As the_geom) As foo;
SELECT ST_AsText((ST_Dump(the_geom)).geom)
FROM
(SELECT ST_LocateBetween(
ST_GeomFromText('MULTILINESTRING M ((1 2 3, 3 4 2, 9 4 3),
(1 2 3, 5 4 5))'),1.5, 3) As the_geom) As foo;
SELECT ST_AsEWKT(
ST_ForceRHR(
'POLYGON((0 0 2, 5 0 2, 0 5 2, 0 0 2),(1 1 2, 1 3 2, 3 1 2, 1 1 2))'
)
);
SELECT ST_HasArc(ST_Collect('LINESTRING(1 2, 3 4, 5 6)', 'CIRCULARSTRING(1 1, 2 3, 4 5, 6
7, 5 6)'));
select 'cd1', 'LINESTRING(0 0,0 10)'::geometry <->
'LINESTRING(4 0,4 10)'::geometry;
SELECT ST_AsEWKT(ST_Force3DZ(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5
6 2)')));
SELECT ST_AsEWKT(ST_Force3DZ('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))'));
SELECT ST_X(ST_GeomFromEWKT('POINT(1 2 3 4)'));
SELECT ST_Y(ST_Centroid(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)')));
SELECT ST_AsText(ST_ConvexHull(
ST_Collect(
ST_GeomFromText('MULTILINESTRING((100 190,10 8),(150 10, 20 30))'),
ST_GeomFromText('MULTIPOINT(50 5, 150 30, 50 10, 10 10)')
)) );
SELECT ST_3DExtent(foo.the_geom) As b3extent
FROM (SELECT ST_MakePoint(x,y,z) As the_geom
FROM generate_series(1,3) As x
CROSS JOIN generate_series(1,2) As y
CROSS JOIN generate_series(0,2) As Z) As foo;
SELECT ST_3DExtent(foo.the_geom) As b3extent
FROM (SELECT ST_Translate(ST_Force_3DZ(ST_LineToCurve(ST_Buffer(ST_MakePoint(x,y),1))),0,0,
z) As the_geom
FROM generate_series(1,3) As x
CROSS JOIN generate_series(1,2) As y
CROSS JOIN generate_series(0,2) As Z) As foo;
SELECT ST_3DMaxDistance(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 10000)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546
20)'),2163)
) As dist_3d,
ST_MaxDistance(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 10000)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546
20)'),2163)
) As dist_2d;
SELECT ST_Zmflag(ST_GeomFromEWKT('LINESTRING(1 2, 3 4)'));
SELECT ST_Zmflag(ST_GeomFromEWKT('CIRCULARSTRING(1 2 3, 3 4 3, 5 6 3)'));
SELECT ST_Zmflag(ST_GeomFromEWKT('POINT(1 2 3 4)'));
SELECT ST_AsText(ST_OffsetCurve(
ST_GeomFromText(
'LINESTRING(164 16,144 16,124 16,104
16,84 16,64 16,
44 16,24 16,20 16,18 16,17 17,
16 18,16 20,16 40,16 60,16 80,16
100,
16 120,16 140,16 160,16 180,16
195)'),
15, 'quad_segs=4 join=round'));
SELECT ST_AsText(ST_Collect(
ST_OffsetCurve(geom, 15, 'quad_segs=4 join=round'),
ST_OffsetCurve(ST_OffsetCurve(
geom,
-30, 'quad_segs=4 join=round'),
-15, 'quad_segs=4 join=round')
)
) As parallel_curves
FROM ST_GeomFromText(
'LINESTRING(164 16,144 16,124 16,104
16,84 16,64 16,
44 16,24 16,20 16,18 16,17 17,
16 18,16 20,16 40,16 60,16 80,16
100,
16 120,16 140,16 160,16 180,16
195)') As geom;
SELECT ST_AsText(
ST_PointN(
column1,
generate_series(1, ST_NPoints(column1))
))
FROM ( VALUES ('LINESTRING(0 0, 1 1, 2 2)'::geometry) ) AS foo;
SELECT ST_AsText(ST_PointN(ST_GeomFromText('CIRCULARSTRING(1 2, 3 2, 1 2)'),2));
SELECT 'valid wkb compound curve 1', ST_asEWKT(ST_GeomFromEWKB(decode('0109000000020000000102000000030000009FE5797057376340E09398B1B2373BC05AAE0A165F0963409F6760A2493D3DC0DB6286DFB057634082D8A1B32F843EC0010200000004000000DB6286DFB057634082D8A1B32F843EC075B4E4D0C60C634031FA5D1A371540C0D7197CED9B636340A3CB59A7630A41C050F4A72AC0FB6240974769FCE3CF41C0', 'hex')));
SELECT 'valid ewkb curve polygon 5', ST_AsEWKT(ST_GeomFromEWKB(decode('010a00000002000000010200000007000000ccdf061ad9f3614054093e6d99093ec0ab9085dbb6dd614081540229216040c0ebd7a828c33e62409bf026782a7e41c0000000c06bb2624000000020adb440c08e632f616ead6240c9f7b0bf1dd33dc09011eec0de4362407dd6672f76323ec0ccdf061ad9f3614054093e6d99093ec00109000000030000000108000000030000006844c4fe011b6240342e2993e0423fc0d45daf9d93066240c4a0c305d62240c000000080ac31624000000020fbbe40c001020000000200000000000080ac31624000000020fbbe40c0000000e0107f6240000000c0a10440c0010800000003000000000000e0107f6240000000c0a10440c04e1c0c14624c6240bf3fb6405c793fc06844c4fe011b6240342e2993e0423fc0', 'hex')));
SELECT ST_AsEWKT(ST_ForceCollection('POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3
1,1 1 1))'));
SELECT ST_AsText(ST_ForceCollection('CIRCULARSTRING(220227 150406,2220227 150407,220227
150406)'));
SELECT ST_AsText(house_loc) As as_text_house_loc,
startstreet_num +
CAST( (endstreet_num - startstreet_num)
* ST_LineLocatePoint(street_line, house_loc) As integer) As street_num
FROM
(SELECT ST_GeomFromText('LINESTRING(1 2, 3 4)') As street_line,
ST_MakePoint(x*1.01,y*1.03) As house_loc, 10 As startstreet_num,
20 As endstreet_num
FROM generate_series(1,3) x CROSS JOIN generate_series(2,4) As y)
As foo
WHERE ST_DWithin(street_line, house_loc, 0.2);
SELECT ST_AsText(ST_LineInterpolatePoint(foo.the_line, ST_LineLocatePoint(foo.the_line,
ST_GeomFromText('POINT(4 3)'))))
FROM (SELECT ST_GeomFromText('LINESTRING(1 2, 4 5, 6 7)') As the_line) As foo;
SELECT ST_Perimeter(ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416))', 2249));
SELECT ST_Perimeter(ST_GeomFromText('MULTIPOLYGON(((763104.471273676 2949418.44119003,
763104.477769673 2949418.42538203,
763104.189609677 2949418.22343004,763104.471273676 2949418.44119003)),
((763104.471273676 2949418.44119003,763095.804579742 2949436.33850239,
763086.132105649 2949451.46730207,763078.452329651 2949462.11549407,
763075.354136904 2949466.17407812,763064.362142565 2949477.64291974,
763059.953961626 2949481.28983009,762994.637609571 2949532.04103014,
762990.568508415 2949535.06640477,762986.710889563 2949539.61421415,
763117.237897679 2949709.50493431,763235.236617789 2949617.95619822,
763287.718121842 2949562.20592617,763111.553321674 2949423.91664605,
763104.471273676 2949418.44119003)))', 2249));
SELECT ST_Perimeter(geog) As per_meters, ST_Perimeter(geog)/0.3048 As per_ft
FROM ST_GeogFromText('POLYGON(( 71.1776848522251 42.3902896512902, 71.1776843766326
42.3903829478009,
71.1775844305465 42.3903826677917, 71.1775825927231 42.3902893647987, 71.1776848522251
42.3902896512902))') As geog;
SELECT ST_Perimeter(geog) As per_meters, ST_Perimeter(geog,false) As per_sphere_meters,
ST_Perimeter(geog)/0.3048 As per_ft
FROM ST_GeogFromText('MULTIPOLYGON((( 71.1044543107478 42.340674480411, 71.1044542869917
42.3406744369506,
71.1044553562977 42.340673886454, 71.1044543107478 42.340674480411)),
(( 71.1044543107478 42.340674480411, 71.1044860600303 42.3407237015564, 71.1045215770124
42.3407653385914,
71.1045498002983 42.3407946553165, 71.1045611902745 42.3408058316308, 71.1046016507427
42.340837442371,
71.104617893173 42.3408475056957, 71.1048586153981 42.3409875993595, 71.1048736143677
42.3409959528211,
71.1048878050242 42.3410084812078, 71.1044020965803 42.3414730072048,
71.1039672113619 42.3412202916693, 71.1037740497748 42.3410666421308,
71.1044280218456 42.3406894151355, 71.1044543107478 42.340674480411)))') As geog;
SELECT ST_IsCollection('LINESTRING(0 0, 1 1)'::geometry);
SELECT ST_IsCollection('MULTIPOINT EMPTY'::geometry);
SELECT ST_IsCollection('MULTIPOINT((0 0), (42 42))'::geometry);
SELECT ST_3DLength(ST_GeomFromText('LINESTRING(743238 2967416 1,743238 2967450 1,743265
2967450 3,
743265.625 2967416 3,743238 2967416 3)',2249));
SELECT 'numInteriorRing01', ST_numInteriorRing(ST_Geomfromewkt('CURVEPOLYGON(CIRCULARSTRING(
-2 0,
-1 -1,
0 0,
1 -1,
2 0,
0 2,
-2 0),
(-1 0,
0 0.5,
1 0,
0 1,
-1 0))')) ;
SELECT 'numInteriorRing02', ST_numInteriorRing(ST_Geomfromewkt('CURVEPOLYGONM(CIRCULARSTRING(
-2 0 0,
-1 -1 2,
0 0 4,
1 -1 6,
2 0 8,
0 2 4,
-2 0 0),
(-1 0 2,
0 0.5 4,
1 0 6,
0 1 4,
-1 0 2))')) ;
SELECT 'numInteriorRing03', ST_numInteriorRing(ST_Geomfromewkt('CURVEPOLYGON(CIRCULARSTRING(
-2 0 0,
-1 -1 1,
0 0 2,
1 -1 3,
2 0 4,
0 2 2,
-2 0 0),
(-1 0 1,
0 0.5 2,
1 0 3,
0 1 3,
-1 0 1))'));
SELECT ST_AsEWKT(
ST_ForceRHR(
'POLYGON((0 0 2, 5 0 2, 0 5 2, 0 0 2),(1 1 2, 1 3 2, 3 1 2, 1 1 2))'
)
);
SELECT ST_AsText(ST_InteriorRingN(the_geom, 1)) As the_geom
FROM (SELECT ST_BuildArea(
ST_Collect(ST_Buffer(ST_Point(1,2), 20,3),
ST_Buffer(ST_Point(1, 2), 10,3))) As the_geom
) as foo;
SELECT ST_IsEmpty(ST_GeomFromText('GEOMETRYCOLLECTION EMPTY'));
SELECT ST_IsEmpty(ST_GeomFromText('POLYGON EMPTY'));
SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))'));
SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))')) = false;
SELECT ST_3DDFullyWithin(geom_a, geom_b, 10) as D3DFullyWithin10, ST_3DDWithin(geom_a,
geom_b, 10) as D3DWithin10,
ST_DFullyWithin(geom_a, geom_b, 20) as D2DFullyWithin20,
ST_3DDFullyWithin(geom_a, geom_b, 20) as D3DFullyWithin20 from
(select ST_GeomFromEWKT('POINT(1 1 2)') as geom_a,
ST_GeomFromEWKT('LINESTRING(1 5 2, 2 7 20, 1 9 100, 14 12 3)') as geom_b) t1;
SELECT ST_NRings(the_geom) As Nrings, ST_NumInteriorRings(the_geom) As ninterrings
FROM (SELECT ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))') As the_geom) As foo
;
SELECT ST_Touches('LINESTRING(0 0, 1 1, 0 2)'::geometry, 'POINT(1 1)'::geometry);
SELECT ST_Touches('LINESTRING(0 0, 1 1, 0 2)'::geometry, 'POINT(0 2)'::geometry);
SELECT ST_AsText(ST_StartPoint('LINESTRING(0 1, 0 2)'::geometry));
SELECT ST_StartPoint('POINT(0 1)'::geometry) IS NULL AS is_null;
SELECT ST_AsEWKT(ST_StartPoint('LINESTRING(0 1 1, 0 2 2)'::geometry));
SELECT ST_AsText(
ST_GeogFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@')
);
SELECT ST_AsSVG(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));
SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227
150505,220227 150406)')));
SELECT ST_AsEWKT(ST_CurveToLine(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227
150505 2,220227 150406 3)')));
SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227
150505,220227 150406)'),2));
SELECT ST_AsText(ST_Collect(ST_GeomFromText('POINT(1 2)'),
ST_GeomFromText('POINT(-2 3)') ));
SELECT ST_AsText(ST_Collect(ST_GeomFromText('POINT(1 2)'),
ST_GeomFromText('POINT(1 2)') ) );
SELECT ST_AsEWKT(ST_Collect(ST_GeomFromEWKT('POINT(1 2 3)'),
ST_GeomFromEWKT('POINT(1 2 4)') ) );
SELECT ST_AsText(ST_Collect(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227
150505,220227 150406)'),
ST_GeomFromText('CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)')));
SELECT ST_AsText(ST_Collect(ARRAY[ST_GeomFromText('LINESTRING(1 2, 3 4)'),
ST_GeomFromText('LINESTRING(3 4, 4 5)')])) As wktcollect;
SELECT ST_GeomFromKML('
<LineString>
<coordinates>-71.1663,42.2614
-71.1667,42.2616</coordinates>
</LineString>');
SELECT ST_OrderingEquals(ST_GeomFromText('LINESTRING(0 0, 10 10)'),
ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)'));
SELECT ST_OrderingEquals(ST_GeomFromText('LINESTRING(0 0, 10 10)'),
ST_GeomFromText('LINESTRING(0 0, 0 0, 10 10)'));
SELECT ST_OrderingEquals(ST_Reverse(ST_GeomFromText('LINESTRING(0 0, 10 10)')),
ST_GeomFromText('LINESTRING(0 0, 0 0, 10 10)'));
SELECT ST_CoordDim('CIRCULARSTRING(1 2 3, 1 3 4, 5 6 7, 8 9 10, 11 12 13)');
SELECT ST_CoordDim(ST_Point(1,2));
select ST_makebox2d('SRID=3;POINT(0 0)', 'SRID=3;POINT(1 1)');
select ST_makebox2d('POINT(0 0)', 'SRID=3;POINT(1 1)');
SELECT '#178a', ST_XMin(ST_MakeBox2D(ST_Point(5, 5), ST_Point(0, 0)));
SELECT '#178b', ST_XMax(ST_MakeBox2D(ST_Point(5, 5), ST_Point(0, 0)));
SELECT ST_NumPatches(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0
0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )'));
SELECT ST_AsText(ST_Intersection('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::
geometry));
SELECT ST_AsText(ST_Intersection('POINT(0 0)'::geometry, 'LINESTRING ( 0 0, 0 2 )'::
geometry));
SELECT ST_AsEWKT(geom) As the_geom, path
FROM ST_DumpRings(
ST_GeomFromEWKT('POLYGON((-8149064 5133092 1,-8149064 5132986 1,-8148996 5132839
1,-8148972 5132767 1,-8148958 5132508 1,-8148941 5132466 1,-8148924 5132394 1,
-8148903 5132210 1,-8148930 5131967 1,-8148992 5131978 1,-8149237 5132093 1,-8149404
5132211 1,-8149647 5132310 1,-8149757 5132394 1,
-8150305 5132788 1,-8149064 5133092 1),
(-8149362 5132394 1,-8149446 5132501 1,-8149548 5132597 1,-8149695 5132675 1,-8149362
5132394 1))')
) as foo;
SELECT ST_IsClosed('LINESTRING(0 0, 1 1)'::geometry);
SELECT ST_IsClosed('LINESTRING(0 0, 0 1, 1 1, 0 0)'::geometry);
SELECT ST_AsText(ST_PointOnSurface('POINT(0 5)'::geometry));
SELECT ST_AsText(ST_PointOnSurface('LINESTRING(0 5, 0 10)'::geometry));
SELECT ST_AsText(ST_PointOnSurface('POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))'::geometry));
SELECT ST_AsEWKT(ST_PointOnSurface(ST_GeomFromEWKT('LINESTRING(0 5 1, 0 0 1, 0 10 2)')));
SELECT ST_GeomFromEWKT('SRID=4269;LINESTRING(-71.160281 42.258729,-71.160837
42.259113,-71.161144 42.25932)');
SELECT ST_GeomFromEWKT('SRID=4269;MULTILINESTRING((-71.160281 42.258729,-71.160837
42.259113,-71.161144 42.25932))');
SELECT ST_RelateMatch('101202FFF', 'TTTTTTFFF') ;
SELECT mat.name, pat.name, ST_RelateMatch(mat.val, pat.val) As satisfied
FROM
( VALUES ('Equality', 'T1FF1FFF1'),
('Overlaps', 'T*T***T**'),
('Within', 'T*F**F***'),
('Disjoint', 'FF*FF****') As pat(name,val)
CROSS JOIN
( VALUES ('Self intersections (invalid)', '111111111'),
('IE2_BI1_BB0_BE1_EI1_EE2', 'FF2101102'),
('IB1_IE1_BB0_BE0_EI2_EI1_EE2', 'F11F00212')
) As mat(name,val);
SELECT ST_AsEWKT(ST_FlipCoordinates(GeomFromEWKT('POINT(1 2)')));
SELECT ST_AsText('01030000000100000005000000000000000000
000000000000000000000000000000000000000000000000
F03F000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000');
SELECT ST_NDims(ST_GeomFromText('POINT(1 1)')) As d2point,
ST_NDims(ST_GeomFromEWKT('POINT(1 1 2)')) As d3point,
ST_NDims(ST_GeomFromEWKT('POINTM(1 1 0.5)')) As d2pointm;
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0');
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 0);
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10);
SELECT ST_AsText(
ST_ShortestLine('POINT(100 100)
'::geometry,
'LINESTRING (20 80, 98
190, 110 180, 50 75 )'::geometry)
) As sline;
SELECT ST_AsEWKT(ST_3DShortestLine(line,pt)) AS shl3d_line_pt,
ST_AsEWKT(ST_ShortestLine(line,pt)) As shl2d_line_pt
FROM (SELECT 'MULTIPOINT(100 100 30, 50 74 1000)'::geometry As pt,
'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 900)'::
geometry As line
) As foo;
SELECT ST_Npoints(the_geom) As np_before, ST_NPoints(ST_SimplifyPreserveTopology(the_geom
,0.1)) As np01_notbadcircle, ST_NPoints(ST_SimplifyPreserveTopology(the_geom,0.5)) As
np05_notquitecircle,
ST_NPoints(ST_SimplifyPreserveTopology(the_geom,1)) As np1_octagon, ST_NPoints(
ST_SimplifyPreserveTopology(the_geom,10)) As np10_square,
ST_NPoints(ST_SimplifyPreserveTopology(the_geom,100)) As np100_stillsquare
FROM (SELECT ST_Buffer('POINT(1 3)', 10,12) As the_geom) As foo;
SELECT ST_AsText(ST_Segmentize(
ST_GeomFromText('MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45 -33,-46 -32))')
,5)
);
SELECT ST_AsText(ST_Segmentize(ST_GeomFromText('POLYGON((-29 28, -30 40, -29 28))'),10));
SELECT ST_AsEWKT(ST_3DLongestLine(line,pt)) AS lol3d_line_pt,
ST_AsEWKT(ST_LongestLine(line,pt)) As lol2d_line_pt
FROM (SELECT 'POINT(100 100 30)'::geometry As pt,
'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 1000)'::
geometry As line
) As foo;
SELECT ST_AsEWKT(ST_3DLongestLine(line,pt)) AS lol3d_line_pt,
ST_AsEWKT(ST_LongestLine(line,pt)) As lol2d_line_pt
FROM (SELECT 'MULTIPOINT(100 100 30, 50 74 1000)'::geometry As pt,
'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 900)'::
geometry As line
) As foo;
SELECT ST_AsEWKT(ST_3DLongestLine(poly, mline)) As lol3d,
ST_AsEWKT(ST_LongestLine(poly, mline)) As lol2d
FROM (SELECT ST_GeomFromEWKT('POLYGON((175 150 5, 20 40 5, 35 45 5, 50 60 5,
100 100 5, 175 150 5))') As poly,
ST_GeomFromEWKT('MULTILINESTRING((175 155 2, 20 40 20, 50 60 -2, 125
100 1, 175 155 1),
(1 10 2, 5 20 1))') As mline ) As foo;
select PostGIS_GEOS_Version();
SELECT ST_AsText(the_geom) as line, ST_AsText(ST_Reverse(the_geom)) As reverseline
FROM
(SELECT ST_MakeLine(ST_MakePoint(1,2),
ST_MakePoint(1,10)) As the_geom) as foo;
SELECT tbl1.column1, tbl2.column1, tbl1.column2 @ tbl2.column2 AS contained
FROM
( VALUES
(1, 'LINESTRING (1 1, 3 3)'::geometry)) AS tbl1,
( VALUES
(2, 'LINESTRING (0 0, 4 4)'::geometry),
(3, 'LINESTRING (2 2, 4 4)'::geometry),
(4, 'LINESTRING (1 1, 3 3)'::geometry)) AS tbl2;
SELECT ST_AsText(
ST_SharedPaths(
ST_GeomFromText('MULTILINESTRING((26 125,26 200,126 200,126 125,26 125),
(51 150,101 150,76 175,51 150))'),
ST_GeomFromText('LINESTRING(151 100,126 156.25,126 125,90 161, 76 175)')
)
) As wkt;
SELECT ST_AsText(
ST_SharedPaths(
ST_GeomFromText('LINESTRING(76 175,90 161,126 125,126 156.25,151 100)'),
ST_GeomFromText('MULTILINESTRING((26 125,26 200,126 200,126 125,26 125),
(51 150,101 150,76 175,51 150))')
)
) As wkt;
select 'bd1', 'LINESTRING(0 0,0 10,10 10)'::geometry <#>
'LINESTRING(6 2,6 8)'::geometry;
select 'bd2', 'LINESTRING(0 0,0 10,10 10)'::geometry <#>
'LINESTRING(11 0,19 10)'::geometry; SELECT edge_id, (dp).path[1] As index, ST_AsText((dp).geom) As wktnode
FROM (SELECT 1 As edge_id
, ST_DumpPoints(ST_GeomFromText('LINESTRING(1 2, 3 4, 10 10)')) AS dp
UNION ALL
SELECT 2 As edge_id
, ST_DumpPoints(ST_GeomFromText('LINESTRING(3 5, 5 6, 9 10)')) AS dp
) As foo;
SELECT path, ST_AsText(geom)
FROM (
SELECT (ST_DumpPoints(g.geom)).*
FROM
(SELECT
'GEOMETRYCOLLECTION(
POINT ( 0 1 ),
LINESTRING ( 0 3, 3 4 ),
POLYGON (( 2 0, 2 3, 0 2, 2 0 )),
POLYGON (( 3 0, 3 3, 6 3, 6 0, 3 0 ),
( 5 1, 4 2, 5 2, 5 1 )),
MULTIPOLYGON (
(( 0 5, 0 8, 4 8, 4 5, 0 5 ),
( 1 6, 3 6, 2 7, 1 6 )),
(( 5 4, 5 8, 6 7, 5 4 ))
)
)'::geometry AS geom
) AS g
) j;
SELECT ST_AsEWKT(ST_GeometryN(p_geom,3)) As geom_ewkt
FROM (SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE(
((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1))
)') AS p_geom ) AS a;
SELECT ST_GeoHash(ST_SetSRID(ST_MakePoint(-126,48),4326));
SELECT ST_GeoHash(ST_SetSRID(ST_MakePoint(-126,48),4326),5);
SELECT ST_Relate(ST_GeometryFromText('POINT(1 2)'), ST_Buffer(ST_GeometryFromText('POINT(1
2)'),2));
SELECT ST_Relate(ST_GeometryFromText('LINESTRING(1 2, 3 4)'), ST_GeometryFromText('
LINESTRING(5 6, 7 8)'));
SELECT ST_Relate(ST_GeometryFromText('POINT(1 2)'), ST_Buffer(ST_GeometryFromText('POINT(1
2)'),2), '0FFFFF212');
SELECT ST_Relate(ST_GeometryFromText('POINT(1 2)'), ST_Buffer(ST_GeometryFromText('POINT(1
2)'),2), '*FF*FF212');
SELECT ST_InterpolatePoint('LINESTRING M (0 0 0, 10 0 20)', 'POINT(5 5)');
SELECT ST_Extent(foo.the_geom) As b3extent
FROM (SELECT ST_Translate(ST_Force_2D(ST_LineToCurve(ST_Buffer(ST_MakePoint(x,y),1))),0,0) As the_geom
FROM generate_series(1,3) As x
CROSS JOIN generate_series(1,2) As y
) As foo;
SELECT ST_Extent(foo.the_geom) As b3extent
FROM (SELECT ST_MakePoint(x,y) As the_geom
FROM generate_series(1,3) As x
CROSS JOIN generate_series(1,2) As y
) As foo;
SELECT ST_LineCrossingDirection(foo.line1
, foo.line2) As l1_cross_l2 ,
ST_LineCrossingDirection(foo.
line2, foo.line1) As l2_cross_l1
FROM (
SELECT
ST_GeomFromText('LINESTRING(25 169,89
114,40 70,86 43)') As line1,
ST_GeomFromText('LINESTRING(171 154,20
140,71 74,161 53)') As line2
) As foo;
SELECT ST_LineCrossingDirection(foo.line1
, foo.line2) As l1_cross_l2 ,
ST_LineCrossingDirection(foo.
line2, foo.line1) As l2_cross_l1
FROM (
SELECT
ST_GeomFromText('LINESTRING(25 169,89
114,40 70,86 43)') As line1,
ST_GeomFromText('LINESTRING (171 154,
20 140, 71 74, 2.99 90.16)') As line2
) As foo;
SELECT
ST_LineCrossingDirection(foo.
line1, foo.line2) As l1_cross_l2 ,
ST_LineCrossingDirection(foo.
line2, foo.line1) As l2_cross_l1
FROM (
SELECT
ST_GeomFromText('LINESTRING(25 169,89
114,40 70,86 43)') As line1,
ST_GeomFromText('LINESTRING (20 140, 71
74, 161 53)') As line2
) As foo;
SELECT ST_LineCrossingDirection(foo.line1
, foo.line2) As l1_cross_l2 ,
ST_LineCrossingDirection(foo.
line2, foo.line1) As l2_cross_l1
FROM (SELECT
ST_GeomFromText('LINESTRING(25
169,89 114,40 70,86 43)') As line1,
ST_GeomFromText('LINESTRING(2.99
90.16,71 74,20 140,171 154)') As line2
) As foo;
SELECT ST_GMLToSQL('
<gml:LineString srsName="EPSG:4269">
<gml:coordinates>
-71.16028,42.258729 -71.160837,42.259112 -71.161143,42.25932
</gml:coordinates>
</gml:LineString>');
SELECT
ST_ConcaveHull(
ST_Union(ST_GeomFromText
('POLYGON((175 150, 20 40,
50 60, 125 100,
175 150))'),
ST_Buffer(ST_GeomFromText
('POINT(110 170)'), 20)
), 1)
As convexhull;
SELECT
ST_ConcaveHull(
ST_Union(ST_GeomFromText
('POLYGON((175 150, 20 40,
50 60, 125 100,
175 150))'),
ST_Buffer(ST_GeomFromText
('POINT(110 170)'), 20)
), 0.9)
As target_90;
SELECT ST_ConcaveHull(ST_Collect(geom),
0.99)
FROM (SELECT (ST_DumpPoints(ST_GeomFromText(
'MULTIPOINT(14 14,34 14,54 14,74 14,94
14,114 14,134 14,
150 14,154 14,154 6,134 6,114 6,94 6,74
6,54 6,34 6,
14 6,10 6,8 6,7 7,6 8,6 10,6 30,6 50,6
70,6 90,6 110,6 130,
6 150,6 170,6 190,6 194,14 194,14 174,14
154,14 134,14 114,
14 94,14 74,14 54,14 34,14 14)'))).geom ) foo;
SELECT ST_AsEWKT('0103000020E61000000100000005000000000000000000000000000000000000000000000000000000000000000000F03F000000000000F03F000000000000F03F000000000000F03F000000000000000000000000000000000000000000000000'::geometry);
SELECT ST_AsEWKT('0108000080030000000000000060 E30A4100000000785C0241000000000000F03F0000000018E20A4100000000485F024100000000000000400000000018E20A4100000000305C02410000000000000840');
SELECT ST_AsText(ST_LineToCurve(foo.the_geom)) As curvedastext,ST_AsText(foo.the_geom) As
non_curvedastext
FROM (SELECT ST_Buffer('POINT(1 3)'::geometry, 3) As the_geom) As foo;
SELECT ST_AsEWKT(ST_LineToCurve(ST_GeomFromEWKT('LINESTRING(1 2 3, 3 4 8, 5 6 4, 7 8 4, 9
10 4)')));
SELECT ST_BuildArea(ST_Collect(smallc,bigc))
FROM (SELECT
ST_Buffer(
ST_GeomFromText('POINT(100 90)'), 25) As smallc,
ST_Buffer(ST_GeomFromText('POINT(100 90)'), 50) As bigc) As foo;
SELECT ST_BuildArea(ST_Collect(line,circle))
FROM (SELECT
ST_Buffer(
ST_MakeLine(ST_MakePoint(10, 10),ST_MakePoint(190, 190)),
5) As line,
ST_Buffer(ST_GeomFromText('POINT(100 90)'), 50) As circle) As foo;
SELECT ST_BuildArea(
ST_Collect(ST_ExteriorRing(line),ST_ExteriorRing(circle))
)
FROM (SELECT ST_Buffer(
ST_MakeLine(ST_MakePoint(10, 10),ST_MakePoint(190, 190))
,5) As line,
ST_Buffer(ST_GeomFromText('POINT(100 90)'), 50) As circle) As foo;
SELECT ST_AsText(ST_MinimumBoundingCircle(
ST_Collect(
ST_GeomFromEWKT('LINESTRING(55 75,125 150)'),
ST_Point(20, 80)), 8
)) As wktmbc;
SELECT ST_AsEWKT(
ST_ExteriorRing(
ST_GeomFromEWKT('POLYGON((0 0 1, 1 1 1, 1 2 1, 1 1 1, 0 0 1))')
)
);
SELECT tbl1.column1, tbl2.column1, tbl1.column2 <<| tbl2.column2 AS below
FROM
( VALUES
(1, 'LINESTRING (0 0, 4 3)'::geometry)) AS tbl1,
( VALUES
(2, 'LINESTRING (1 4, 1 7)'::geometry),
(3, 'LINESTRING (6 1, 6 5)'::geometry),
(4, 'LINESTRING (2 3, 5 6)'::geometry)) AS tbl2;
SELECT gid, ST_IsValidReason(the_geom) as validity_info
FROM
(SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), ST_Accum(f.line)) As the_geom, gid
FROM (SELECT ST_Buffer(ST_MakePoint(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid
FROM generate_series(-4,6) x1
CROSS JOIN generate_series(2,5) y1
CROSS JOIN generate_series(1,8) z1
WHERE x1 > y1*0.5 AND z1 < x1*y1) As e
INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_MakePoint(x1*10,y1), z1)),y1
*1, z1*2) As line
FROM generate_series(-3,6) x1
CROSS JOIN generate_series(2,5) y1
CROSS JOIN generate_series(1,10) z1
WHERE x1 > y1*0.75 AND z1 < x1*y1) As f
ON (ST_Area(e.buff) > 78 AND ST_Contains(e.buff, f.line))
GROUP BY gid, e.buff) As quintuplet_experiment
WHERE ST_IsValid(the_geom) = false
ORDER BY gid
LIMIT 3;
SELECT ST_IsValidReason('LINESTRING(220227 150406,2220227 150407,222020 150410)');
SELECT ST_AsEWKT(a.geom), ST_HasArc(a.geom)
FROM ( SELECT (ST_Dump(p_geom)).geom AS geom
FROM (SELECT ST_GeomFromEWKT('COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0
1))') AS p_geom) AS b
) AS a;
SELECT (a.p_geom).path[1] As path, ST_AsEWKT((a.p_geom).geom) As geom_ewkt
FROM (SELECT ST_Dump(ST_GeomFromEWKT('POLYHEDRALSURFACE(
((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1
1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)))') ) AS p_geom ) AS a;
SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt
FROM
(SELECT
ST_Dump( ST_GeomFromEWKT('TIN (((
0 0 0,
0 0 1,
0 1 0,
0 0 0
)), ((
0 0 0,
0 1 0,
1 1 0,
0 0 0
))
)') ) AS gdump
) AS g;
SELECT ST_Polygon(ST_GeomFromText('LINESTRING(75.15 29.53,77 29,77.6 29.5, 75.15 29.53)'),
4326);
SELECT ST_AsEWKT(ST_Polygon(ST_GeomFromEWKT('LINESTRING(75.15 29.53 1,77 29 1,77.6 29.5 1,
75.15 29.53 1)'), 4326));
SELECT ST_3DDWithin(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546
20)'),2163),
126.8
) As within_dist_3d,
ST_DWithin(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546
20)'),2163),
126.8
) As within_dist_2d;
SELECT round(CAST(ST_Distance_Sphere(ST_Centroid(the_geom), ST_GeomFromText('POINT(-118 38)',4326)) As numeric),2) As dist_meters,
round(CAST(ST_Distance(ST_Transform(ST_Centroid(the_geom),32611),
ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As
dist_utm11_meters,
round(CAST(ST_Distance(ST_Centroid(the_geom), ST_GeomFromText('POINT(-118 38)', 4326)) As
numeric),5) As dist_degrees,
round(CAST(ST_Distance(ST_Transform(the_geom,32611),
ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As
min_dist_line_point_meters
FROM
(SELECT ST_GeomFromText('LINESTRING(-118.584 38.374,-118.583 38.5)', 4326) As the_geom)
as foo;
SELECT ST_AsEWKT(ST_RotateZ(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), pi()/2));
SELECT ST_AsEWKT(ST_RotateZ(the_geom, pi()/2))
FROM (SELECT ST_LineToCurve(ST_Buffer(ST_GeomFromText('POINT(234 567)'), 3)) As the_geom)
As foo;
SELECT ST_NumPoints(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29
29.07)'));
SELECT ST_ContainsProperly(smallc, bigc) As smallcontainspropbig,
ST_ContainsProperly(bigc,smallc) As bigcontainspropsmall,
ST_ContainsProperly(bigc, ST_Union(smallc, bigc)) as bigcontainspropunion,
ST_Equals(bigc, ST_Union(smallc, bigc)) as bigisunion,
ST_Covers(bigc, ST_ExteriorRing(bigc)) As bigcoversexterior,
ST_ContainsProperly(bigc, ST_ExteriorRing(bigc)) As bigcontainsexterior
FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc,
ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo;
| true |
9b3a6b4816d3f29b3ef85c95eb9e0e75293c68b4 | SQL | robertogs2/bases | /Project2/DB_Scripts/6-Security/SecurityTestUser1.sql | UTF-8 | 1,211 | 3.125 | 3 | [] | no_license |
-- User1 permissions were set for BASESTECBAK data base
USE BASESTECBAK;
-- ____________________________
--_____________/Allowed operations for User1\___________
-- Recover data queries
SELECT * FROM Employee;
SELECT * FROM City;
SELECT * FROM Community;
-- Store data queries
INSERT INTO Characteristic
("Name", "Value")
VALUES
('TestUser1Insert', 'TestUser1Insert');
INSERT INTO Country
("Name")
VALUES
('TestUser1Insert');
-- Reverse changes to return DB to its original state
DELETE FROM Characteristic
WHERE Characteristic.Name = 'TestUser1Insert';
DELETE FROM Country
WHERE Country.Name = 'TestUser1Insert';
-- Store Procedures
EXEC GetChain;
-- ______________________________
--_____________/Forbidden operations for User1\___________
-- Recover data queries
SELECT * FROM Park;
SELECT * FROM Person;
-- Store data queries
INSERT INTO AssignedArea
("Name")
VALUES
('Test_User1_Insert');
INSERT INTO Speciality
("Name")
VALUES
('Test_User1_Insert');
-- Reverse changes to return DB to its original state
DELETE FROM AssignedArea
WHERE AssignedArea.Name = 'Test_User1_Insert';
DELETE FROM Speciality
WHERE Speciality.Name = 'Test_User1_Insert';
-- Store Procedures
EXEC GetBeings; | true |
b250fb1323e0cc11cd8ac2dbccc3f0c3875d47b1 | SQL | ituk-ttu/esport-2019-spring-web | /db/src/main/resources/db/migration/V1.1555513347__add_owner_as_member.sql | UTF-8 | 119 | 2.921875 | 3 | [
"MIT"
] | permissive | INSERT INTO TICKET_MEMBERS (ticketId, email)
SELECT T.id, U.email
FROM TICKETS T
LEFT JOIN USERS U on T.ownerId = U.id; | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.