Oracle database using SQL statements
Table primary key generated automatically
Creating a sequence:
-- Create sequence
create sequence BXBILL_PK_SEQUENCE
minvalue 1
maxvalue 9999999999999999999999999999
start with 1
increment by 1
cache 20;
Creating Triggers
create or replace trigger bxbill_pk_tg
before insert
on eam_bxbill
for each row
declare
-- local variables here
begin
select BXBILL_PK_SEQUENCE.NEXTVAL into:new.bxbill_pk from dual;
end ;
insert insert statement
insert into eam_bxbill(BXBILL_DJBH,BXBILL_ZCZZ,BXBILL_SSDW,AMCARDID,BXBILL_COMP,BXBILL_SFJDCL)
values ( '20181008001', 'Baoding good the United States,' 'Baoding Perfect Health Services Limited', 'bssm201809290001', 'Hebei Baoding', 'yes')
Create a time table row automatically generated value
In creattime field, set the date type, the default is set to SYSDATE;
Table row value generated automatically update time
Increase trigger:
create or replace trigger update_tg
before insert or update on EAM_bxbill for each row
begin
select sysdate into:new.update_datetime from dual;
end;
Which EAM_bxbill to be processed table name, update_datetime to update the fields;
Create a view
CREATE OR REPLACE VIEW CHENBEN AS
SELECT
COST_ANALYSIS.year year,
COST_ANALYSIS.month month,
COST_ANALYSIS.center_code Center project code,
project_base_info.center_name center project name,
COST_ANALYSIS.procom_code coding project company,
project_base_info.procom_name project company name,
COST_ANALYSIS.prodep_code project department coding,
project_base_info.prodep_name project department name,
COST_ANALYSIS.income_rec income _ excluding tax receivable,
COST_ANALYSIS.income_pay paid-income _ excluding tax,
The total number of COST_ANALYSIS.headcount,
COST_ANALYSIS.per_capital_output per capita GDP,
COST_ANALYSIS.manufa_gz manufacturing costs _ wages,
COST_ANALYSIS.manufa_jbf manufacturing costs _ overtime,
COST_ANALYSIS.manufa_wxy_syx_gzzrx manufacturing costs _ five insurance payments,
COST_ANALYSIS.manufa_zgflf manufacturing costs _ welfare,
COST_ANALYSIS.manufa_zjf manufacturing costs _ Depreciation,
COST_ANALYSIS.manufa_txf manufacturing costs _ amortization,
COST_ANALYSIS.manufa_zlf manufacturing costs _ rental fees,
COST_ANALYSIS.manufa_ylf manufacturing costs _ fuel costs,
COST_ANALYSIS.manufa_xlf manufacturing costs _ repairs,
COST_ANALYSIS.manufa_bxftx manufacturing costs _ _ amortization of premiums,
COST_ANALYSIS.manufa_njf manufacturing costs _ annual fees,
COST_ANALYSIS.manufa_lqf manufacturing costs _ the road toll,
COST_ANALYSIS.manufa_txf2 manufacturing costs _ communications,
COST_ANALYSIS.manufa_sf manufacturing costs _ water,
COST_ANALYSIS.manufa_df manufacturing costs _ electricity,
COST_ANALYSIS.manufa_clf_zyyp manufacturing costs _ cost of materials _ Work supplies,
COST_ANALYSIS.manufa_clf_wxbj manufacturing costs _ cost of materials _ maintenance spare parts,
COST_ANALYSIS.manufa_lbyp manufacturing costs _ labor supplies,
COST_ANALYSIS.manufa_ljqyfy manufacturing costs _ garbage removal costs,
COST_ANALYSIS.manufa_lwf manufacturing costs _ labor,
COST_ANALYSIS.manufa_tmcfy manufacturing costs _ landfill costs,
COST_ANALYSIS.manufa_sgpc manufacturing costs _ accident compensation,
COST_ANALYSIS.manufa_ghjf manufacturing costs _ union funds,
COST_ANALYSIS.manufa_qt manufacturing costs _ Other,
COST_ANALYSIS.manufa_qtdbz manufacturing costs _ other notes,
COST_ANALYSIS.manufa_yycbhj total operating costs,
COST_ANALYSIS.admicost_gz administrative costs _ wages,
COST_ANALYSIS.admicost_jbf administrative expenses _ overtime,
COST_ANALYSIS.admicost_wxyj_syx_gzzrx administrative expenses _ five insurance gold,
COST_ANALYSIS.admicost_zgflf administrative costs _ welfare,
COST_ANALYSIS.admicost_zjf administrative expenses _ depreciation,
COST_ANALYSIS.admicost_txf management fees _ amortization,
COST_ANALYSIS.admicost_zlf management fees _ rental fees,
COST_ANALYSIS.admicost_ylf management fees _ fuel costs,
COST_ANALYSIS.admicost_wxf management fees _ maintenance,
COST_ANALYSIS.admicost_bxftx administrative expenses insurance _ _ amortization,
COST_ANALYSIS.admicost_njf management fees _ annual fees,
COST_ANALYSIS.admicost_lqf administrative costs _ the road toll,
COST_ANALYSIS.admicost_txf2 management fees _ communications,
COST_ANALYSIS.admicost_sf administrative expenses _ water,
COST_ANALYSIS.admicost_df administrative expenses _ electricity,
COST_ANALYSIS.admicost_bgf administrative expenses _ office expenses,
COST_ANALYSIS.admicost_yyzdf administrative expenses _ Hospitality Operations,
COST_ANALYSIS.admicost_clf administrative expenses _ travel,
COST_ANALYSIS.admicost_jtf management fees _ transportation,
COST_ANALYSIS.admicost_hyf management fees _ conference fees,
COST_ANALYSIS.admicost_ydf management fees _ postal fees,
COST_ANALYSIS.admicost_ghjf administrative expenses _ union funds,
COST_ANALYSIS.admicost_qt administrative expenses _ Other,
COST_ANALYSIS.admicost_qtdbz administrative expenses _ other notes,
COST_ANALYSIS.admicost_sum management Total cost,
COST_ANALYSIS.totalcost_month this month, the total cost _ not including tax,
COST_ANALYSIS.expenses_lastyear monthly total costs expensed in the year last year together,
COST_ANALYSIS.market_cost market _ a business expense,
COST_ANALYSIS.taxes taxes and surcharges,
COST_ANALYSIS.assets_loss impairment losses,
COST_ANALYSIS.financial_cost financial costs,
COST_ANALYSIS.income_tax income tax,
COST_ANALYSIS.gross_profit gross profit,
COST_ANALYSIS.gross_profit_margin gross margin,
COST_ANALYSIS.retained_profit net profit,
COST_ANALYSIS.retained_profit_margin net profit margin,
COST_ANALYSIS.Report_notes statements Notes
FROM COST_ANALYSIS join project_base_info on COST_ANALYSIS.PRODEP_CODE=project_base_info.prodep_code
with read only;
Creating an index
单一索引:Create Index <Index-Name> On <Table_Name>(Column_Name);
create index INFOR_INDEX on PROJECT_BASE_INFO (USER_CODE)
select * from COST_ANALYSIS
where PROCOM_CODE ='0902'
0.226 seconds; (before indexing)
0.170 seconds; (the index)
create index cost_index on COST_ANALYSIS(PROCOM_CODE)
Authorization Form user permissions to another user
Command: grant xxx authority the Table to the USER ON
Grant the SELECT, INSERT, Update, the Delete, All ON table name to the user name
, for example: the test authority to query a table giving the user tom
grant select on test to tom
Log in with system users, passwords oracle
grant select on lcsg609999.amcard to fanruan;
New User Authorization
grant connect, resource to username;
Accuracy: specifies the maximum number of decimal digits to the right of the decimal point can be stored and left
length: storing the number of bytes occupied by this
- M : accuracy, the total length of the data;
- D : scale length after the decimal point;
- coding select assets, count (*) from No_JDC_view group by encoding assets having count (*)> 1
Whether to repeat the query field
Create a foreign key
ALTER TABLE books ADD CONSTRAINT FK_Book_categoryid FOREIGN KEY(categoryId ) REFERENCES Category(id);
With pl / sql wizard little more convenient.
Foreign key field, a length field must be consistent with the type of reference; last names are also the same.
Delete table
Right-table delete, without prompting, too dangerous.
With sql:
Drop table table;
Backup table
create table <backup table name> as select * from <name table entry to be backed>
E.g:
create table project_type201812 as select * from project_type
Field Length Setting principles
Oracle character set GBK16, a 2-byte characters is provided;
A UTF-8 characters 3 bytes
select u.name, length(u.name), lengthb(u.name) from var u;
Character length byte length
Query the current database character sets;
select userenv('language') from dual;
Computer coding system
Coding American ASCII (American Standard Code for Information Interchange, American Standard Code for Information Interchange)
China gbk coding known as They are called " DBCS " (Double Byte Charecter the Set double-byte character set)
Unified Unicode Unicode, Unicode
Implementation using the most widely on the Internet unicode utf-8, designed to transmit coded. Features: variable-length encoding, unified Without Borders
Modify pl / sql sql window font size
Packet sequencing
1 Overview
Group By "understood in a literal sense is based," "data packets specified rules, the so-called packet is a" By dataset "is divided into a number of" small area ", and for a number of" data small area " deal with.
2, the original table
3, Group By simple
Example 1
select number of categories, sum (amount) as and
from A
group by category
Return results in the table below, in fact subtotals.
4、Group By 和 Order By
Example 2
select number of categories, sum (quantity) AS and
from A
group by category
order by sum(数量) desc
Return results in the following table
In Access can not use "order by the sum of the number desc", but in SQL Server can.
Rownum automatically get the line number
Select rownnum 行号, code,name from depetment
Get the current date
Gets the date field in select to_char (sysdate, 'yyyy') as year from dua
Acquiring date field month select to_char (sysdate, 'mm') as month from dual
Acquiring date field date select to_char (sysdate, 'dd') as day from dua
Acquisition last month, next month
select to_char(add_months(trunc(sysdate),-1),'yyyymm') from dual;
- last month
select to_char(add_months(trunc(sysdate),1),'yyyymm') from dual;
- next month
select to_char(add_months(trunc(sysdate),-12),'yyyy') from dual;
--last year
select to_char(add_months(trunc(sysdate),12),'yyyy') from dual;
--next year
dual is a virtual table, is used to select the rules of grammar constitute, oracle to ensure that there is always only a dual record. We can use it for many things, as follows:
1, view the current user, you can execute the following statement in SQL Plus
select user from dual;
2, used to call system function
select to_char (sysdate, 'yyyy-mm-dd hh24: mi: ss') from dual; - the current system time
select SYS_CONTEXT ( 'USERENV', 'TERMINAL') from dual; - obtaining a host name
select SYS_CONTEXT ( 'USERENV', 'language') from dual; - to obtain the current locale
select dbms_random.random from dual; - obtaining a random number
3, gets the next value of the sequence or the current value, with the following statement
select your_sequence.nextval from dual; - get the next value of the sequence your_sequence
select your_sequence.currval from dual; - get the current value of the sequence your_sequence
4, can be used as a calculator
select 7*9 from dual;
1group by order by mixed, sorted aggregate functions
SELECT
b.title as category,
sum (a.weight) / 1000000 as recovered material by weight
FROM
recycle_order_recycle_detail a,
recycle_type b
where a.recycle_type_id=b.id
AND DATE_SUB(CURDATE(), INTERVAL 0 DAY) <= date(a.ctime)
group by b.title, b.title order by weight of recovered material desc
Temporary tables
Sometimes because a large query results and the need to connect different forms of table lookup talk to other tables, it is written down only if the entire sql query looks bloated and efficiency is very low, Oracle provides a way to query results into
Writing temporary tables can speak query results are stored in a temporary table stand, here I only remember one kind of session-level usage, the results of the query in the current session data is stored in a temporary table, the end of the (closed) session data was remove
Session level
CREATE GLOBAL TEMPORARY TABLE tmptable
ON COMMIT PRESERVE ROWS
AS
Select * from table
Should pay within a month from the date of the query
select aa.patents_name as proprietary name,
cc.details_name as 类型,
dd.details_name as expense type,
bb.expenses_yjfrq as should the payment date,
bb.expenses_sjjfrq as actual payment date
from patents aa, expenses bb, record_details cc, record_details dd
where aa.patents_pk = bb.patents_pk
and aa.patents_type = cc.details_pk
and bb.expenses_fylx = dd.details_pk
and bb.expenses_fylx = '53'
and to_char(bb.expenses_yjfrq,'yyyy/mm/dd')=to_char(add_months(trunc(sysdate),1),'yyyy/mm/dd')
The current date plus 7 days
to_char(trunc(sysdate+7),'yyyy/mm/dd')
When doing keyword sql field names, field names need to add quotation marks to use;
Cross-table data update
update amsubs
set amsubs.AMTXKH=(select amcardsdhz.TXKH from amcardsdhz where amcardsdhz.AMCARDID='b233aab0dfe94520b9d16427d2b405be')
where amsubs.subamcardid='b233aab0dfe94520b9d16427d2b405be'
The number of real-time intelligent hardware statistics
- intelligent hardware statistics -
select
amtype.typecode asset class code,
amtype.typename asset class name,
The number of the sum (amcard.amqty) as and
from amcard
left join amtype on amcard.AMTypeID=amtype.typeid
left join Amusestate on amcard.Amstate=Amusestate.stateid
left join lsbzdw on amcard.AcctCompID=lsbzdw.lsbzdw_dwbh
left join lsbmzd on (amcard.AcctCompID=lsbmzd.lsbmzd_dwbh) and (amcard.AcctDeptID=lsbmzd.lsbmzd_bmbh)
left join HROrgInfo hr_org on (amcard.Usecompid=hr_org.orgcode) and hr_org.orgtype='0'
left join HROrgInfo hr_dep on (amcard.usedeptid=hr_dep.nm) and hr_dep.orgtype='1'
where amtype.typename in
( 'Card machine', 'walkie-talkie', 'intelligent bracelet', 'Sound Box', 'Go ahead kiosks', 'Go ahead Pavilion (ready disable)')
/*and
Amusestate.Statecode='1000'
*/
- the top encoded as belonging to the idle state assets coding
group by amtype.typecode,amtype.typename
union all connected
SELECT
'Maintenance' expense type,
wxf.amcardid asset master key,
wxf.wxfy main expense,
wxf.gsf time charge,
wxf.bjf spare parts costs,
'' Fuel costs,
'' Premium,
wxf.amwxgd_zdrq single system date
FROM
amwxgd wxf
WHERE
wxf.amcardid != ' '
AND wxf.wxfy IS NOT NULL
AND wxf.gsf IS NOT NULL
AND wxf.bjf IS NOT NULL
UNION ALL
SELECT
'Upkeep' expense type,
byf.amcardid asset master key,
byf.ambyjlnr_jcfy main expense,
byf.gsf time charge,
byf.bjf spare parts costs,
'' Fuel costs,
'' Premium,
ambyjl.ambyjl_zdrq single system date
FROM
ambyjlnr steak,
ambyjl
WHERE
byf.ambyjlnr_djid = ambyjl.ambyjl_djid
AND byf.amcardid IS NOT NULL
SQL UNION operator UNION ALL and
UNION operation result set operator for combining two or more of the SELECT statement.
Please note that the interior of the UNION SELECT statement must have the same number of columns. The columns must also have similar data types. Meanwhile, the order of columns in each SELECT statement must be the same.
SQL UNION Syntax
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
Note : By default, UNION operator to select a different value. If you allow duplicate values, use UNION ALL.
SQL UNION ALL syntax
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
In addition, UNION result set is always equal to the column names in the first column name UNION SELECT statement.
Order by the group by using in combination
PLSQL landscaping design
SELECT
( CASE WHEN zc.acctcompid IS NOT NULL THEN zc.acctcompid WHEN zc.acctcompid IS NULL THEN zc.usecompid END ) 公司主键,
sum ( "view_zcwb". Main expenses) + sum ( "view_zcwb". time charge) + sum ( "view_zcwb". spares fee) Total cost
FROM
"view_zcwb",
amcard zc
WHERE
zc.amcardid (+) = "view_zcwb". asset master key
AND (zc.acctcompid IS NOT NULL or zc.usecompid is not null)
AND to_char ( "view_zcwb". Manufactured by a single date, 'yyyy') = '2018'
GROUP BY
( CASE WHEN zc.acctcompid IS NOT NULL THEN zc.acctcompid WHEN zc.acctcompid IS NULL THEN zc.usecompid END )
ORDER BY
sum ( "view_zcwb". Main expenses) + sum ( "view_zcwb". time charge) + sum ( "view_zcwb". spares fee) desc
Case when grammar
SELECT
(CASE WHEN bb.details_name IS NOT NULL THEN bb.details_name else ' to a soft' END) patent type,
-- bb.details_name,
count( aa.patents_pk )
FROM
patents aa,
record_details bb
WHERE
aa.patents_type = bb.details_pk ( + )
GROUP BY
bb.details_name
SELECT
( CASE WHEN bb.details_name IS NOT NULL THEN bb.details_name WHEN bb.details_name IS NULL THEN '软著' END ) 专利类型,
-- bb.details_name,
count( aa.patents_pk )
FROM
patents aa,
record_details bb
WHERE
aa.patents_type = bb.details_pk ( + )
GROUP BY
bb.details_name
union Usage:
union operator for combining two or more select statements result set. internal union select statement must have the same number of columns. The columns must also have similar data types. Meanwhile, the order of columns in each of the select statement must be the same.
By default, union operator to select a different value. If you allow duplicate values, use the union all.
When multiple connections Table conditions:
left join record_details r1 on (SANITATION_DATA.COUNTRY_CLEANING_STANDARD=r1.DETAILS_CODE) and r1.record_pk='22'
left join record_details r2 on (SANITATION_DATA.City_price_type=r2.DETAILS_CODE) and r2.record_pk='23'