Five sensory organs of human body such as ears which senses sound in the environment nose which senses smell in the environment and tongue which senses taste of any food atom that we eat skin which senses the hotness or coldness of other body and eyes which senses different colors seen from it in

The same way sensor is an electronic device which detects and responds to some type of input from the physical environment and converts this output signals to in human readable display now let’s have a look

 

What is a Sensor?

In general, sensor is known as a Detector.

The basic definition of,

A sensor is an electronic equipment that is used to detect and observe the physical activities and pass the notifcation/signal to other electrical control devices.

In other words, a sensor is an electronic device that can transform energy from one form to another form. So, it is also called a Transducer.

The main function of the sensor is to identify and communicate with physical quantities such as temperature, heat, pressure, distance, moisture, gas, and so on.

 

And it provides output in the form of electrical signal to connected control systems.

 

You can easily understand this from following simple block diagram.

For example, in an automation system, the sensor is the most important equipment that provides an input to the programmable logic controller (PLC).

In daily life applications, commercial and industrial devices, the educational projects, different types of sensor are used with a specific role.

What are the different types of Sensors?

Sensors are split up into four main categories. Such as,

  • Analog Sensor
  • Digital Sensor
  • Active Sensor
  • Passive Sensor

Each category is having the different types of sensor as follows.

 

1. Temperature Sensor (온도 센서)

Temperature sensor uses to detect the temperature and heat energy and convert it into an electrical signal (in form of voltage or current).

There are several types of temperature sensor used.

  • Thermometer
  • Thermocouple
  • Resistance Temperature Detector (RTD)
  • Thermistor Temperature Sensor
  • Semiconductor Temperature Sensor
  • Vibrating Wire Temperature Sensor

The temperature sensor is used in a computer, refrigerator, automobile, medical device, cooking appliances, electrical motor, etc.

 

2. Pressure Sensor (압력 센서)

Pressure sensor is called Pressure Transducer or Pressure Transmitter or Piezometer.

A pressure sensor detects the pressure of air, gas, water and provides electrical signal to the controller.

 

According to different uses and many more features, it is divided into different parts like,

  • Vacuum Pressure Sensor
  • Absolute Pressure Sensor
  • Gauge Pressure Sensor
  • Differential Pressure Sensor

Pressure sensors are used in many systems like pneumatic, hydraulic, vacuum systems, etc.

 

3. Touch Sensor

The touch sensor is called a Tactile sensor. It is an electronic sensor that is used for detecting and recording physical touch.

Capacitive touch sensor, resistive touch sensor are the best example of touch sensor.

 

It is used in industrial applications like switches for turn on/off light, remote control by the air conditioner (AC), door open/close operation, elevator, and robotics, smartphones, so on.

An oximeter is one of the best example of a touch-based sensor to detect oxygen levels in the human body.

In this COVID pandemic, Pulse Oximeter is in huge demand. It is easy to handle and operate, even at your home. You can easily buy an online Pulse Oximeter.

 

4. Image Sensor

The image sensor is an electronic device that is used to detect the image pixels and provide information to the display devices.

There are analog and digital types of sensor. Generally, an electronic image sensor is classified into two main types.

  • Charge-Coupled Device (CCD)
  • Active Pixel Sensor 

For the digital camera, closed-circuit television (CCTV), medical imaging equipment, thermal imaging devices, radar, sonar, etc., image sensors are used.

 

5. Motion Sensor

Motion sensor measures and records physical activities or movements. It is classified into different types.

  • Active Motion Sensor
  • Passive Motion Sensor
  • Tomographic Motion Sensor
  • Gesture Motion Sensor

The motion sensor is used in home security, automatic doors operation, microwaves, robotics, ultrasonic waves, gesture detector, etc.

 

6. Light Sensor

Light sensor is a photoelectric device. This sensor detects and converts the brightness or luminescence of light or photon into an electrical signal.

There are three types of light sensor.

  • Photoresistor or Light Dependent Resistor (LDR)
  • Photodiode
  • Phototransistor

It is widely used in the solar system, automobile, agriculture sector (automatic sprinkler system), and electronic-based project device like Arduino.

 

7. Vibration Sensor

Sometimes, vibration sensor is known as Piezoelectric Sensor.

The vibration sensor detects and records any movement or activities. And it provides data or signals to connected machines or systems.

 

This sensor helps to send acknowledgement if there is any hazardous activity.

 

In an industrial area such as gas and oil, food and beverage, mining, metalworking, paper, wind power, power generation, the vibration sensords are needed.

 

8. Humidity Sensor

Humidity sensor is also known as a Hygrometer.

For detecting moisture in air and soil, the humidity sensor is very essential. Mostly, it is used in Air Conditioner (AC) system.

WS1 Pro is an example of the wireless humidity sensor.

 

9. Proximity Sensor (근접센서)

Proximity sensor can easily detect nearby objects without any physical touch. It is divided into different types like-

  • Capacitive Proximity Sensor
  • Inductive Proximity Sensor

It is widely used in smartphones, tablet computers, machines, robotic systems, roller coasters, etc.

 

10. Colour Sensor

Colour sensor is the type of photoelectric sensor.

It helps to sense the color of an object and recognize the color mark. This sensor uses RGB (red, green, and blue) color scale.

SEN-11195 is the best example of the color sensor.

For colour painting and printing, cosmetic material, textile area, medical diagnosis, computer color monitor, and the process control, colour sensor is used.

 

11. Radiation Sensor

A radiation sensor is an electronics instrument that senses and measures the radiation particles like alpha, beta, gamma, neutrons, X-ray.

Also, it senses electromagnetic radiation like waves, cosmic radiation (sunlight).

Radiation sensor includes three different type.

  • Gas-filled Radiation Sensor
  • Scintillation Radiation Sensor
  • Solid-state Radiation Sensor

This sensor is used for nuclear energy, medical imaging modalities, and monitoring of environmental radioactivity.

 

12. Level Sensor

The main role of the level sensor is to measure the level or height of different materials like solid, liquid, and gaseous.

It is classified into different parts.

  • Laser Level Sensor
  • Float Sensor
  • Capacitive Level Sensor
  • Resistive Level Sensor
  • Ultrasonic Level Sensor
  • Hydrostatic Level Sensor
  • Optical Level Sensor
  • Electromagnetic Level Sensor

It is widely used in vessel, container, water tank, fuel tank bin, etc for water level check.

 

13. Position Sensor

Position sensor determines the displacement and the position (like linear and rotational).

Basically, position sensor available in the different types.

  • Optical Position Sensor
  • Linear Position Sensor
  • Rotary Position Sensor
  • Inductive Position Sensor
  • Capacitive Position Sensor
  • Fiber-Optic Position Sensor
  • Ultrasonic Position Sensor

For example, a potentiometer contains the rotational position sensor that can vary with angular movement.

The position sensor is used in domestic and industrial applications like door closing/opening, valve monitoring, motor controlling, throttles for controlling the flow of fuel or power to an engine.

 

14. Gas or Smoke Sensor

Gas sensor is used to detect different types of gasses, toxic or explosive gasses, smoke in the air. Some of these sensors are also capable to measure gas concentration. 

Gas or smoke sensor is divided into three parts.

  • Optical Type Smoke Sensor
  • Ionization Type Smoke Sensor
  • Laser Type Smoke Sensor

Smoke sensor is used in plant, industries, buildings, ships, airplanes, etc.

 

15. Flame Sensor

The flame sensor easily detects fire or flame of nearby materials. These detected signals are passed to the connected control devices.

It is used in industrial areas for an alarm system, natural gas plant, fire suppression system and Arduino based design fire detector project.

 

16. Leak Sensor

Leak sensor is used in a closed vessel or vaccum for detecting water leakage, fluid leakage, air leakage, etc.

As per the working role, it is divided into two main parts.

  • Spot Leak Sensor
  • Flow Leak Sensor

17. Accelerometer (가속도계)

Accelerometer is an instrument that measure motion acceleration or velocity.

It is used in many applications such as hand gesture controlled robot, navigation system for aircraft and missiles, process and control system, vehicle acceleration, and other rotating electronic equipment like a turbine, roller, fan, compressor, pump.

 

18. Tilt Sensor

Tilt sensor detects and varies with an angular movement, angular slope, angular motion, axes of the reference plane.

It is mostly used for monitoring the angle and auto-rotating operation in mobile, tablet, hand-held games, boats, vehicles, and aircraft, etc.

 

19. Mark Sensor

Mark sensor works as photoelectric type of sensor. It is used to sense colour mark on presence of an objects.

Mark sensor is widely used in printing and packaging industries.

 

20. Flow Sensor or Float Sensor

Flow sensor measures and detects virtually any process fluid. This detected data will be provided to the controller system.

It is used in industrial area, power generating instruments, power plant, etc.

 

산업 모니터링에 관한 다른 Contents도 확인 하세요. 

 

'ForBeginner' 카테고리의 다른 글

2-4. 센서와 변환기  (0) 2021.05.19
2-3. Analog & Digital Sensors  (0) 2021.05.19
8-7. MSSQL(View)  (0) 2021.05.18
8-5. 트리거(Trigger)  (0) 2021.05.18
8-2-1. MSSQL (Join)  (0) 2021.05.17
  • View는 기존 Table에 모든 Data가 있는데, 의미있는 Data로 다시 Rearrage할때 사용된다. 
  • 자주 조회하는 Data를 Select Group 과 Select join을 이용하여 View로 만들어 놓으면 편리하게 사용할 수 있다. 

 뷰(View)란 무엇인가? 

  1. 뷰는 사용자에게 접근이 허용된 자료만을 제한적으로 보여주기 위해 하나 이상의 기본 테이블로부터 유도된, 이름을 가지는 가상 테이블이다.
  2. 뷰는 저장장치 내에 물리적으로 존재하지 않지만 사용자에게 있는 것처럼 간주된다.
  3. 뷰는 데이터 보정작업, 처리과정 시험 등 임시적인 작업을 위한 용도로 활용된다.
  4. 뷰는 조인문의 사용 최소화로 사용상의 편의성을 최대화 한다.

뷰(View)의 특징

  1. 뷰는 기본테이블로부터 유도된 테이블이기 때문에 기본 테이블과 같은 형태의 구조를 사용하며, 조작도 기본 테이블과 거의 같다.
  2. 뷰는 가상 테이블이기 때문에 물리적으로 구현되어 있지 않다.
  3. 데이터의 논리적 독립성을 제공할 수 있다.
  4. 필요한 데이터만 뷰로 정의해서 처리할 수 있기 때문에 관리가 용이하고 명령문이 간단해진다.
  5. 뷰를 통해서만 데이터에 접근하게 하면 뷰에 나타나지 않는 데이터를 안전하게 보호하는 효율적인 기법으로 사용할 수 있다.
  6. 기본 테이블의 기본키를 포함한 속성(열) 집합으로 뷰를 구성해야지만 삽입, 삭제, 갱신, 연산이 가능하다.
  7. 일단 정의된 뷰는 다른 뷰의 정의에 기초가 될 수 있다.
  8. 뷰가 정의된 기본 테이블이나 뷰를 삭제하면 그 테이블이나 뷰를 기초로 정의된 다른 뷰도 자동으로 삭제된다.

뷰(View)사용시 장 단점

장점

  1. 논리적 데이터 독립성을 제공한다.
  2. 동일 데이터에 대해 동시에 여러사용자의 상이한 응용이나 요구를 지원해 준다.
  3. 사용자의 데이터관리를 간단하게 해준다.
  4. 접근 제어를 통한 자동 보안이 제공된다.

단점

  1. 독립적인 인덱스를 가질 수 없다.
  2. ALTER VIEW문을 사용할 수 없다. 즉 뷰의 정의를 변경할 수 없다.
  3. 뷰로 구성된 내용에 대한 삽입, 삭제, 갱신, 연산에 제약이 따른다.

 

 간단한 예제 

뷰 정의문

--문법-- CREATE VIEW 뷰이름[(속성이름[,속성이름])]AS SELECT문; --고객 테이블에서 주소가 서울시인 고객들의 성명과 전화번호를 서울고객이라는 뷰로 만들어라-- CREATE VIEW 서울고객(성명, 전화번호) AS SELECT 성명 전화번호 FROM 고객 WHERE 주소 = '서울시';

 

뷰 삭제문

 뷰는 ALTER문을 사용하여 변경할 수 없으므로 필요한 경우는 삭제한 후 재생성한다.

--문법-- DROP VIEW 뷰이름 RESTRICT or CASCADE --서울고객이라는 뷰를 삭제해라-- DROP VIEW 서울고객 RESTRICT;

RESTRICT : 뷰를 다른곳에서 참조하고 있으면 삭제가 취소된다.

CASCADE : 뷰를 참조하는 다른 뷰나 제약 조건까지 모두 삭제된다.

 

산업 모니터링에 관한 다른 Contents도 확인 하세요. 

'ForBeginner' 카테고리의 다른 글

2-3. Analog & Digital Sensors  (0) 2021.05.19
2-2. Types of Sensors  (0) 2021.05.18
8-5. 트리거(Trigger)  (0) 2021.05.18
8-2-1. MSSQL (Join)  (0) 2021.05.17
8-2. MSSQL(Group by, Having)  (0) 2021.05.17
  • 트리거는 테이블의 Data가 변경시에 사용한다.
  • A Table의 트리거를 사용하여 B Table에 insert할 경우에는 B Table의 Primary key를 잘 선택 해야 한다. 
  • B Table의 Key로 인해서, Trigger의 동작이 Error나면, A Table의 Data도 insert되지 않는다. 
  • A Table의 트리거를 사용하여 Romote Server에 insert하지 않아야 한다. 
  • Connection이 끊어졌을경우, Trigger는 Error나게 되고, 소실된 Data를 찾을 수 없다. 
  • Remote서버에 insert할 경우에는 Procedure를 이용하여 작업한다. 

 

 

1. 트리거(Trigger)란?

 

 

 

 

트리거(Trigger)란 영어로 방아쇠라는 뜻인데, 방아쇠를 당기면 그로 인해 총기 내부에서 알아서 일련의 작업을 실행하고 총알이 날아갑니다. 이처럼 데이터베이스에서도 트리거(Trigger)는 특정 테이블에 INSERT, DELETE, UPDATE 같은 DML 문이 수행되었을 때, 데이터베이스에서 자동으로 동작하도록 작성된 프로그램입니다. 즉! 사용자가 직접 호출하는 것이 아니라, 데이터베이스에서 자동적으로 호출하는 것이 가장 큰 특징입니다. 

 

 

트리거(Trigger)는 테이블과 뷰 데이터베이스 작업을 대상으로 정의할 수 있으며, 전체 트랜잭션 작업에 대해 발생되는 트리거(Trigger)와 각행에 대해 발생되는 트리거(Trigger)가 있습니다.

 

 

2. 트리거(Trigger)가 적용되는 예

 

다음과 같은 상황에서 트리거(Trigger)를 사용할 수 있습니다. 어떤 쇼핑몰에 하루에 수만 건의 주문이 들어옵니다. 주문데이터는 주문일자, 주문상품, 수량, 가격이 있으며, 수천명의 임직원이 일자별, 상품별 총 판매수량과 총 판매가격으로 구성된 주문 실적을 실시간으로 온라인상에 조회를 했을 때, 한사람의 임직원이 조회할 때마다 수만 건의 데이터를 읽고 계산해야합니다. 만약 임직원이 수만명이고, 데이터가 수백만건이라면, 또 거의 동시다발적으로 실시간 조회가 요청된다면 시스템 퍼포먼스가 떨어질 것입니다.

 

따라서! 트리거(Trigger)를 사용하여 주문한 건이 입력될 때마다, 일자별 상품별로 판매수량과 판매금액을 집계하여 집계자료를 보관하도록 만들어보겠습니다. 먼저 관련된 테이블을 생성해보겠습니다. 

테이블은 다음과 같습니다. 주문정보테이블에 실시간으로 데이터가 입력될 때마다 트리거가 발동되어 자동으로 일자별판매집계테이블에 일자별, 상품별 판매수량과 판매금액을 계산해 업데이트 하는 작업을 하도록 하고, 사용자들은 미리 계산된 일자별판매집계테이블을 조회하게 하여 실시간 조회를 지원하게 하는 것입니다. 

 

3. 트리거(Trigger) 구현

 

자, 이제 2개 테이블을 CREATE, DDL을 통해 만들어보겠습니다.

 

CREATE TABLE ORDER_LIST(

    ORDER_DATE  CHAR(8) NOT NULL,

    PRODUCT     VARCHAR2(10) NOT NULL,

    QTY         NUMBER NOT NULL,

    AMOUNT      NUMBER NOT NULL

);

 

CREATE TABLE SALES_PER_DATE(

    SALE_DATE   CHAR(8) NOT NULL,

    PRODUCT     VARCHAR2(10) NOT NULL,

    QTY         NUMBER NOT NULL,

    AMOUNT      NUMBER NOT NULL

 

);

 

SELECT *

FROM ORDER_LIST

 

SELECT *

FROM SALES_PER_DATE

 

조회를 해보면 다음과 같습니다.

 

 

아직 2개 테이블다 데이터가 없음을 확인할 수 있습니다. 

 

이제 트리거(Trigger)를 만들어 보겠습니다. 트리거(Trigger)를 구현하기 위해 우선 절차형 SQL과 PL/SQL을 알아야합니다. 절차형 SQL과 PL/SQL은 따로 글을 올리도록 하고, 오늘은 절차형 SQL과 PL/SQL을 안다는 전제하에 트리거(Trigger)를 구현해보겠습니다.

 

 

 

트리거(Trigger) 처리 절차를 설명하면 다음과 같습니다.

8 ~ 14 Line 

 Trigger를 선언합니다. 

order_list 테이블에 insert가 발생하면 그 이후 each row 즉 각 행에 해당 트리거(Trigger)를 적용한다라는 뜻입니다. 또한, declare 선언문에는 변수를 선언합니다. order_list 테이블에 있는 order_date, product Type에 맞게 o_date, o_prod 변수를 선언합니다.

 

15 ~17 Line

new 는 트리거(Trigger)에서 사용하는 구조체 입니다. new는 새로 입력된 레코드 값을 담고 있습니다.

o_date 에 새로 들어온 order_date 값을 , o_prod 에 새로 들어온 product 값을 저장합니다.

 

18 ~ 26 Line

sales_per_date 테이블에 update 구문을 실행하는데, 기존에 있는 qty, amount 를 누적합해서 다시 Set 합니다. 여기서 where문을 통해 현재 새로 들어온 날짜과 상품이 일치하는 데이터만 해당 update문을 실행하도록 조건을 걸었습니다. 

또한 만약 해당 조건에 모두 해당되지 않는다면, if sql%notfound 구문이 실행됩니다. 기존에 있던 레코드 값이 아니고 전혀 새로운 레코드이기 때문에 insert 구문을 통해 새로 들어온 데이터를 새로 삽입합니다. 

끝으로 / 부분은 트리거(Trigger)를 실행하는 실행명령어입니다.

 

위 구문을 실행하면, 이제 2개 테이블에 트리거(Trigger)가 적용된 것입니다. 

 

이제 order_list 테이블에 레코드를 insert 해서 sales_per_date 테이블에 트리거(Trigger)가 자동으로 동작하여, 데이터 값을 자동으로 계산하고 반영하는지 확인해보겠습니다!

 

ORDER_LIST 테이블에 아래와 같이 데이터 값을 삽입해보겠습니다.

 

-> INSERT INTO ORDER_LIST VALUES('20120901','MONOPACK',10,300000)

 

삽입후 ORDER_LIST, SALES_PER_DATE 테이블 조회를 해보겠습니다.

 

ORDER_LIST 정상적으로 값이 삽입되었습니다. 

트리거에 의해서 SALES_PER_DATE 에도 정상적으로 값이 삽입되어있습니다.

 

자. 다시한번 값을 삽입하고 테이블을 확인해보겠습니다.

 

-> INSERT INTO ORDER_LIST VALUES('20120901','MONOPACK',20,600000);

 

ORDER_LIST 를 조회하면 지금까지 삽입한 값들이 리스트로 있습니다. 

SALES_PER_DATE 테이블은 트리거에 의해서 주문날짜별 상품별 물량과 가격이 합산되어 업데이트 되어있음을 확인할 수 있습니다.

4. 트리거(Trigger)와 트랜잭션(Transaction)의 상관관계

  

이번에는 다른 상품으로 주문 데이터를 입력한 후 두 테이블의 결과를 조회해보고 트랜잭션을 ROLLBACK 해보겠습니다. 판매 데이터의 입력취소가 일어나면, 주문 정보 테이블(ORDER_LIST)과 판매 집계테이블(SALES_PER_DATE )에 동시에 입력(수정) 취소가 일어나는지 확인해보기 위함입니다.

 

 

-> INSERT INTO ORDER_LIST VALUES('20120901','MULTIPACK',10,300000);

 

ORDER_LIST 에 정상적으로 판매 데이터가 삽입되었습니다. 

 

SALES_PER_DATE 테이블은 트리거에 의해 판매날짜별, 상품별 누적 물량과 가격이 업데이트 되었습니다.

 

 

이제 ROLLBACK; 명령어를 실행해보겠습니다. 

ORDER_LIST 테이블에 방금 삽입한 판매데이터가 취소되었습니다.

 

SALES_PER_DATE 테이블에도 똑같이 트리거로 입력된 데이터 정보까지 하나의 트랜잭션으로 인식하여 입력 취소가 되었습니다. 

 

즉, 트리거는 데이터베이스에 의해 자동 호출되지만 결국 INSERT, UPDATE, DELETE 구문과 하나의 트랜잭션 안에서 일어나는 일련의 작업들이라 할 수 있다. 

 (추가로 트리거는 Begin ~ End 절에서 COMMIT , ROLLBACK 을 사용할 수 없다.)

 

산업 모니터링에 관한 다른 Contents도 확인 하세요. 

'ForBeginner' 카테고리의 다른 글

2-2. Types of Sensors  (0) 2021.05.18
8-7. MSSQL(View)  (0) 2021.05.18
8-2-1. MSSQL (Join)  (0) 2021.05.17
8-2. MSSQL(Group by, Having)  (0) 2021.05.17
3-0. 왜 PLC의 이해가 필요한가?  (0) 2021.05.15
  • 중복을 제거하기 위한 Table 디자인으로
  • 분석가능한 의미있는 데이터를 보기 위해서는 반드시 Join의 연습이 필요하다.
  • 아래 다이어그램의 이해를 바탕으로 어떤 Join을 사용할지 결정 해야 하며,
  • 대부분 Inner Join또는 Left Join이 사용된다. 

 

조인(JOIN) ? 

두 개 이상의 테이블을 곱한 결과 집합 이라고 간단히 MSDN에 정의되어있다.

 

JOIN에는 INNER JOIN OUTER JOIN 그리고 CROSS JOIN 이렇게 세가지 종류가 있으며,

실무에서는 대부분 INNER JOIN과  LEFT OUTER JOIN을 사용한다.

 

그림을 보며 하나씩 알아가 보자.

 

 

 

1. INNER JOIN

 

교집합의 결과를 출력해 준다고 생각해주면 쉽다.
그림과 같이 두 테이블의 조건에 모두 만족하는 데이터만 출력해 준다.

 

JOIN유형 생략시 기본적으로 INNER JOIN으로 들어가게 되며,

INNER JOIN시 LEFT,RIGHT같은 기준을 정해주지 않는데, INNER JOIN은 두 조건을 모두 만족하는 결과를 출력해주기 때문에 기준이 되는 테이블을 정해주지 않아도 되기 때문이다.

 

 

2. OUTER JOIN

1) LEFT OUTER JOIN


OUTER JOIN이 INNER JOIN과 다른점은 조건에 맞지 않는 데이터도 표시해 준다는 점이다.

 

LEFT JOIN 수행시 먼저 표기된 좌측 테이블에 해당하는 데이터를 먼저 읽은 후 나중에 표기된 우측 테이블에서 JOIN대상 데이터를 읽어온다. 

즉 A테이블과 B테이블이 있을 때 A가 기준이 되어, A와 B를 비교한다음 B의 JOIN 컬럼에서 같은 값이 있을 때 해당 데이터를 가져오고 B의 JOIN컬럼에서 같은 값이 없는 경우에는 B테이블에서 가져오는 컬럼들은 NULL 값으로 채우는 것이다.

 

참고로 OUTER JOIN은 기본적으로 LEFT OUTER JOIN으로 명시되며, OUTER 키워드는 생략가능하다.

 

2) RIGHT OUTER JOIN

 

RIGHT JOIN은 LEFT JOIN과는 반대로 우측 테이블이 기준이 된다고 생각하면 된다.

 

3) FULL OUTER JOIN

 

JOIN 수행시 좌측과 우측의 모든 데이터를 읽고 JOIN 후 결과를 생성하며, 두 개의 테이블 모두가 기준이 된다.

합집합의 결과를 출력해준다고 생각하면 쉽다.

 

단 UNION ALL이 아닌 UNION 기능과 같으므로 중복 데이터는 삭제된다.

 

 

3. CROSS JOIN

 

 

CROSS JOIN은 상호 조인이라고도 불리며, 한 쪽 테이블의 모든 행들과 다른 테이블의 모든 행을 조인시키는 기능을 한다.

그래서 CROSS JOIN의 결과 개수는 두 테이블의 행의 개수를 곱한 개수가 된다.

 

CROSS문은 모든 행에 대한 결합이 발생하기 때문에 ON구문을 사용할 수 없다.

예전에는 데이터에 대한 카피 후 연산이나 부분합을 구할 때 쓰였지만, 지금은 CUBE나 GROUPPING으로 대체되었고 현재는 잘 쓰지 않는다.

 

산업 모니터링에 관한 다른 Contents도 확인 하세요. 

'ForBeginner' 카테고리의 다른 글

8-7. MSSQL(View)  (0) 2021.05.18
8-5. 트리거(Trigger)  (0) 2021.05.18
8-2. MSSQL(Group by, Having)  (0) 2021.05.17
3-0. 왜 PLC의 이해가 필요한가?  (0) 2021.05.15
3-4. PLC 통신 종류  (0) 2021.05.15
No. 01
그룹 함수

 

그룹 함수는 검색된 여러 행을 이용하여 통계정보를 계산하는 함수이다.

 

 

그룹 함수

함수명 기능 사용
 COUNT  행의 수를 계산한다.   COUNT(컬럼 | *) 
 MAX  값들 중에 최대 값을 반환한다.   MAX(컬럼) 
 MIN  값들 중에 최소 값을 반환한다.   MIN(컬럼) 
 AVG  평균 값을 계산한다.   AVG(컬럼) 
 SUM  총 합계를 계산한다.   SUM(컬럼)
 VARIANCE  분산을 계산한다.   VARIANCE(컬럼) 
 STDDEV  표준편차를 계산한다.   STDDEV(컬럼) 

 

◈ 예제

select count(commission_pct), count(nvl(commission_pct,0))

from employees;

 

보너스를 받지 않는 사람은 commission_pct가 null로 되어있다.

그룹함수는 null 값을 무시하기 때문에 첫 번째의 경우는 보너스를 받는 사람의 수만 계산된 것이고,

두 번째의 경우는 보너스를 받지 않는 사람은 0으로 만들어 줌으로써 전체 사원의 수가 계산된 것이다.

 

select avg(salary) 평균급여1, round(avg(salary)) 평균급여2

from employees;

 

평균급여1 같은 경우 출력 값의 형식은 세션의 설정이나 평균급여2와 같이 단일 함수를 이용해서 지정할 수 있다.

 

select sum(salary) 총액, round(avg(salary)) 평균, count(*) 전체인원

from employees;

 

 

select min(salary), max(salary), min(hire_date), max(hire_date)

from employees;

 

MIN, MAX 함수는 숫자 뿐만 아니라 날짜, 문자에도 사용할 수 있다. 문자의 경우 글자수로 판단한다.

이름을 가지고 MIN, MAX 함수를 사용해 보자.

 

 

 

No. 02
GROUP BY 절

 

특정 속성을 기준으로 그룹화 하여 검색할 때 그룹화 할 속성을 지정한다.

 

기본 구조

SELECT [DISTINCT] 컬럼, 그룹 함수(컬럼)

FROM 테이블명

[WHERE 조건]

[GROUP BY Group대상]

[ORDER BY 정렬대상 [ASC/DESC]]

  • SELECT 절에 그룹 함수와 컬럼명이 같이 기술된 경우 해당 컬럼은 반드시 GROUP BY절에 그룹화 돼야 한다.
  • 결과 값이 정렬되길 원한다면 반드시 ORDER BY 절을 추가한다.3

 

GROUP BY 절은 반드시 그룹함수와 함께 쓰이며 그룹 함수의 결과 값은 GROUP BY 절에 기술된 컬럼의 항목들의 행의 개수에 의해 결정된다.

 

◈ 예제

select department_id, round(avg(salary))

from employees

group by department_id;

 

각 부서별로 사원들 급여의 평균 값이 계산됐다.

일반 언어로 표현한다면 GROUP BY절에 기술된 '컬럼(부서)'별로 평균(그룹 함수)를 계산하라.

 

GROUP BY절의 의미는 그룹 함수를 GROUP BY절에 지정된 컬럼의 값이 같은 행에 대해서 통계 정보를 계산하라는 의미이다.

 

select round(avg(salary))

from employees

group by department_id;

 

GROUP BY절에 기술된 컬럼이 SELECT절에 기술되지 않아도 된다.

위의 경우 부서별로 사원들 급여의 평균 값이 계산됐지만 어느 부서의 평균 값인지 모르기 때문에 쓸모없는 정보나 마찬가지이다.

그러므로 SELECT절에도 GROUP BY절에 기술된 컬럼을 기술하길 권한다.

 

▶ 2개 이상의 그룹화

select department_id 부서번호, job_id 직업, sum(salary)

from employees

group by department_id, job_id

order by department_id;

 

위의 예를 보면 20번 부서가 2번 나와 있는데 이는 같은 부서일지라도 직업이 다르기 때문에 다른 그룹으로 묶인 것이다.

 

select department_id 부서번호, job_id 직업, manager_id 상사번호, sum(salary)

from employees

group by department_id, job_id, manager_id

order by department_id;

 

이번에는 부서번호와 직업이 같은 경우라도 하나의 그룹으로 묶이지 않았다. 이번에는 GROUP BY절에 상사번호까지 기술했기 때문이다.

부서번호, 직업, 상사번호까지 같아야 하나의 그룹으로 묶여 그룹함수의 계산이 이루어진다.

추가로 GROUP BY절을 사용할 경우 ORDER BY절을 사용하기를 권한다.(파악하기 좋게 하기 위해서)

 

즉, 여러 컬럼을 그룹화 할 경우 GROUP BY절에 나열된 컬럼들의 값이 모두 같아야 같은 그룹으로 묶인다.

 

 

▶ 그룹 함수를 중첩해서 사용하는 경우

select department_id 부서번호, max(avg(salary)) 최대평균, min(avg(salary)) 최소평균

from employees

group by department_id;

ORA-00937: not a single-group group function

00937. 00000 -  "not a single-group group function"

 

부서번호를 그룹화 했음에도 불구하고 위의 예제의 경우 에러가 발생한다.

max(avg()), min(avg())는 평균값의 최대 값과 최소 값이므로 어떤 컬럼으로 그룹을 하던 결과는 최대 값 하나 최소 값 하나이다. 그러나 부서번호의 경우 부서별로 그룹을 묶었기 때문에 값이 여러 개이다.

이해가 안된다면 차근차근 생각해보자.

  1. 일단 위의 예제는 부서별로 그룹을 묶었다. 10, 20, 30, … 각 부서마다 그룹으로 묶인 것이다.
  2. 그 후 그룹별로 사원들 급여의 평균 값을 구한다.
  3. 각 그룹별로 평균 값 중에서 최대 값과 최소 값을 구했다. 각각 결과는 하나이다.
  4. select절에 부서번호를 기술했기 때문에 화면에 출력할 때는 그룹으로 묶인 부서들도 보여주어야 한다.

현재는 어느 부서의 최대평균, 최소평균인지는 모른다. 단지 평균값들 중에 최대, 최소가 무엇인지만 검색된 상황이다. 각 부서별로 하나의 행을 차지하고 있을텐데 특정 부서의 옆에 최대평균, 최소평균을 같이 출력한다면 마치 그 부서의 최대평균과 최소평균인 것처럼 보이기 때문에 잘못된 정보가 되버린다. 그래서 이런 상황이 나오지 않도록 예제처럼 SQL문을 작성할 경우 에러로 인식되게 한 것이다.

 

select max(avg(salary)) 최대평균, min(avg(salary)) 최소평균

from employees

group by department_id;

 

정리하면 그룹 함수가 중첩된 경우 GROUP BY절에 기술한 컬럼도 출력 할 수 없다.

 

 

 

No. 03
HAVING 절

 

HAVING 절은 해석상 WHERE 절과 동일하다. 단 조건 내용에 그룹 함수를 포함하는 것만을 포함한다.

일반 조건은 WHERE 절에 기술하지만 그룹 함수를 포함한 조건은 HAVING 절에 기술한다.

 

기본 구조

SELECT [DISTINCT] 컬럼, 그룹 함수(컬럼)

FROM 테이블명

[WHERE 조건]

[GROUP BY Group대상]

[HAVING 그룹 함수 포함 조건]

[ORDER BY 정렬대상 [ASC/DESC]]

  • HAVING 절은 GROUP BY 절 뒤에 기술한다.
  • HAVING 절의 조건은 그룹 함수를 포함해야 한다.

 

◈ 예제

select department_id 부서번호, round(avg(salary)) 평균급여

from employees

group by department_id

having avg(salary) < 7000;

 

SQL문장에서 일반 조건은 WHERE절에 기술하지만 조건에 그룹 함수가 포함된 경우에는 HAVING절에 기술해야 한다.

WHERE절에 그룹 함수가 포함된 조건을 기술하면 에러가 발생한다.

 

select department_id 부서번호, sum(salary) 급여총액

from employees

group by department_id

having job_id != 'IT_PROG';

ORA-00979: not a GROUP BY expression

00979. 00000 -  "not a GROUP BY expression"

 

반대로 HAVING 절에 일반 조건을 기술하면 에러가 발생한다.

그러나 GROUP BY에 기술된 컬럼에 대한 일반 조건은 HAVING절에 기술 가능하다. 하지만 그렇게 되면 SQL문을 해석하기 힘들기 때문에 기술하지 않는 것이 좋다.

 

일반 조건은 WHERE 절에 그룹 함수를 포함한 조건은 HAVING 절에 기술한다.

 

select job_id, sum(salary) 급여총액

from employees

where job_id not like '%REP%'

group by job_id

having sum(salary) > 13000

order by sum(salary);

 

GROUP BY 와 HAVING 절까지 기술한 SELECT 구문을 해석해보자.

  1. from 절에 기술한 테이블에서
  2. where 절에 기술한 조건에 해당하는 내용들만 정리하고
  3. 정리된 내용들을 가지고 group by 절에 나열된 컬럼에 대해서 그룹을 만든다.
  4. 만들어진 그룹별로 having절에 기술된 그룹함수로 계산하여 having절 조건에 맞는 그룹만 추리고
  5. 추려진 그룹들을 order by 절에 잇는 조건으로 정렬시킨다.
  6. 마지막으로 select절에 있는 그룹화된 컬럼 또는 그룹함수를 화면에 출력한다.

산업 모니터링에 관한 다른 Contents도 확인 하세요. 

'ForBeginner' 카테고리의 다른 글

8-5. 트리거(Trigger)  (0) 2021.05.18
8-2-1. MSSQL (Join)  (0) 2021.05.17
3-0. 왜 PLC의 이해가 필요한가?  (0) 2021.05.15
3-4. PLC 통신 종류  (0) 2021.05.15
3-3. PLC 모듈 종류  (0) 2021.05.14

 

  • 일반적으로
  • Sensor의 설치 및 PLC와 의 결선은 A Enginner가, 
  • 설비의 Controller의 PLC, Touch Screen은 B Engineer가, 
  • 모니터링 프로그램 개발은 C Engineer가 하게 되는데, 
  • Sensor의 값이 이상이 있는 것은 C Engineer가 설치한 모니터링 프로그램으로 파악하게 된다. 
  • 고객은 이상현상을 모니터링 프로그램에서 발견하기 때문에
  • Sensor 및 Cable이 이상이 있는지, 
  • 설비 Controller의 프로그램 이상인지, 
  • 모니터링 프로그램의 Bug인지 판단 하지 못하고, 모니터링 프로그램에서 보이기 때문에 
  • C Engineer에게 연락을 하게 된다.

 

  • 어떤 곳에게 문제가 발생했는지 판단 하지 못하면, 
  • 해결하기 까지 시간이 많이 소요되고, 
  • Engineer간의 Scope 다툼으로 이어질 수 있기 때문에
  • 어디에세 문제가 발생했는지 정확히 파악하여 해당 Engineer에게 자료를 보내주고,
  • 수정할 수 있도록 Guide할 수 있는 능력이 있어야 한다. 
  • 그러기 위해서 모니터링 프로그램 개발자도 반드시 PLC의 이해가 필요한다. 

산업 모니터링에 관한 다른 Contents도 확인 하세요. 

'ForBeginner' 카테고리의 다른 글

8-2-1. MSSQL (Join)  (0) 2021.05.17
8-2. MSSQL(Group by, Having)  (0) 2021.05.17
3-4. PLC 통신 종류  (0) 2021.05.15
3-3. PLC 모듈 종류  (0) 2021.05.14
3-2. Global SCADA Market by 2024  (0) 2021.05.13

List of PLC Communication Protocols

What are networking protocols used in Industrial Automation?

Here, I am listing the different types of communication protocols used for the automation of processes in PLC.

  1. EtherNet/IP
  2. Profibus
  3. Modbus
  4. Interbus
  5. ProfiNet
  6. ControlNet
  7. DeviceNet
  8. DirectNet
  9. CompoNet
  10. RAPIENet
  11. EtherCAT
  12. MelsecNet
  13. Optomux
  14. DF-1 Protocol
  15. HostLink Protocol
  16. MECHATROLINK
  17. DH- Data Highway
  18. PPI- Point to Point
  19. EtherNet Powerlink
  20. MPI- Multi-Point Interface
  21. EGD- Ethernet Global Data
  22. AS-i- Actuator Sensor Interface
  23. OSGP- Open Smart Grid Protocol
  24. DNP3- Distributed Network Protocol
  25. SDS- Smart Distributed System Protocol
  26. PieP- Process Image Exchange Protocol
  27. SRTP- Service Request Transport Protocol
  28. BSAP- Bristol Standard Asynchronous Protocol
  29. FINS- Factory Interface Network Service Protocol
  30. HART- Highway Addressable Remote Transducer Protocol
  31. Recommended Standard (RS-232, RS- 422, and RS-485) Protocols

What is the Baud Rate?

Baud rate is also known as Communication speed.

The rate of data transmission on the network is called Baud Rate. The unit of Baud Rate is bits/second (b/s).

In simple terms, it is calculated as the “number of data transferred per second”.

Characteristics of PLC Communication Protocols in Table

When PLC modules are connected over the network, the standard communication protocols are used.

The different types of standard communication protocols support different speed (baud rate), distance(network length) and the number of connecting devices (nodes).

# Protocol/Cable Baud Rate Length Node
01 Ethernet 100 Mb/s (Few Km) 255
02 Profibus 5-12 Mb/s 15 Km 127
03 MPI 19.2- 38.4 Kb/s 50 m 32
04 PPI 187.5 Kb/s 500 m 1
05 DH 230.4 Kb/s 3.048 Km 64
06 Control Net 5 Mb/s 30 Km  
07 Device Net 500 Kb/s 0.487 64
08 USB Adapter 57.6 Kb/s 10 m 1
09 PC Adapter 9600 Kb/s 15 m 1
10 RS-232 19.2 Kb/s 10 m 1
11 RS-485 10 Kb/s 1.2 Km 32

Which PLC communication protocol you should use?

  • If you want to communicate with the more number of nodes with more speed, Ethernet is the best choice. 
  • If your network has a length of more than 25 Kilo-meter, you should use the Control Net protocol.

Binary Data Type Conversion for Baud Rate

Binary system based on the bit. Bit is either 0 or 1.

  • 1 Nibble= 4 Bits
  • 1 Byte= 8 Bits
  • 1 Word= 2 Bytes = 16 Bits
  • 1 Double Word= 4 Bytes= 32 Bits

Let’s see, binary data representation diagram.

This is all about topmost PLC communication protocols. And I also covered the basic fundamental parts of protocol like Baud rate (communication speed), network length and the number of nodes supported by each protocol.

 

산업 모니터링에 관한 다른 Contents도 확인 하세요. 

 

Basics of PLC Modules | Different Types of PLC Modules

Table of Contents

Different types of PLC Modules

A programmable logic computer (PLC) is an industrial digital computer that is generally used to control the process. As it is an industrial computer, a logical program to control the process is prepared in the general computer.

Then this program is transferred to the PLC using cables. This program is stored in the PLC memory.

The logical program is prepared using a programming language called Ladder logic, Statement List, or Functional block diagram. A program is prepared in such a way that the peoples with electrical or instrumentation background can easily understand.

A Programmable Logic Controller consists of various inputs and outputs modules. A PLC monitors the status of switches and sensors using input terminals and based on this status they will give the command to the output devices through the output terminals.

For more details about PLC, you can refer to the article about What is PLC? How does it work?


PLC Hardware

In this article, we are going to see different types of PLC modules. PLC hardware consists of various modules such as,

  • Power Supply Module (PS)
  • CPU
  • Interface Module (IM)
  • Signal Modules (SM)
  • Function Module (FM)
  • Communication Processor (CP)

 

There are mainly two types of PLCs, generally, we can find in the industry, in terms of hardware

1. Fixed PLC or Compact PLC

Compact OR Fixed PLC

All the modules are within a single case. This type of PLC has a fixed number of Input/Output modules.

The power supply, CPU, and communication card are within a single case. From the below image you can get some ideas about the compact or fixed plc.

 

2. Modular PLC

Modular PLC

The name itself suggests that this type of PLC consists of various modules. Inputs and Outputs modules can be easily expanded just by adding the modules.

All the modules are fitted in the rack, that’s why it is also called rack mounted PLC. The below image shows the modular type PLC.


Block Diagram of Siemens PLC Modules

Modular PLCs are the most commonly used PLCs in the industry because it has the reliability to extends the I/Os. There is a rack or chassis in which all the modules are mounted and internally communicated with each other that’s why it is also called “Rack Mounted PLC”.

1) Rack or Chassis

The rack or chassis is the most important hardware part of the PLC.

The rack or chassis allows all the plc modules to be mounted or connected to a communication bus to communicate with the CPU.

The main functions of the rack or chassis are

  • It distributes power evenly
  • It houses different input-output modules
  • It acts as a link between the CPU and different modules

 

2) Power Supply Module (PS)

The power supply module is used to gives the appropriate voltage to a different module as well as the CPU of the PLC system.

The PLC system mostly works with 24V DC voltage, PLC power supply converts line voltage of 100-240 VAC into lower DC voltage generally 24 VDC. PLC power supplies can come in different sizes and ratings based on different plc and applications.

The most common current rating of the power supply module is 5-20 amps for smaller plc systems and it can go up to 50 amps for more complex plc systems.

 

3) Central Processing Unit (CPU)

Central Processing Unit, we can say that this is the brain of this system. The program in the form of logical instructions is stored in the CPU.

All the arithmetic and logical functions are performed in the CPU. It executes the instructions as per the stored program by the user.

The Processor in the CPU is used to do computation like managing the computer’s memory, monitoring the status of inputs, and activating output according to the user’s logical instructions.

The Memory in the CPU is used to store programs and data from the different equipment connected to PLC.

 

4) Interface Module (IM)

The interface module is used when you want to expand input-output modules and you don’t have space for extra modules in the main rack. You have to connect the other rack with the main rack to communicate it with the CPU.

The interface module is used to connect the other racks with the main rack.

 

5) Signal Module (SM)

There are different inputs and outputs are connected with the PLC. These inputs and outputs may be digital or analog.

Field Devices

There are mainly four types of modules are available

  1. Digital Input Module
  2. Digital Output Module
  3. Analog Input Module
  4. Analog Output Module

Sometimes, based on the user requirement, a combination of digital input/output and analog input/output modules are also used.

 

6) Function Module (FM)

It is an optional module and used with the modular types of PLC. This type of module is generally used with a special type of controlling such as,

  • High-Speed Counter Module
  • PID Module
  • Weighing Module

 

7) Communication Processor (CP)

The communication processor module is used mainly for communication with different controllers or devices such as other PLCs, SCADA, HMI, and other controllers.

 

산업 모니터링에 관한 다른 Contents도 확인 하세요. 

 

+ Recent posts