简体   繁体   中英

Query to create new column by analyzing data in 1st column

I am working in SQL Server on a project. and I have this data

Column1

B.Ed

B.Ed

B.Ed

PTC

PTC

Now what I want with this data is that in SQL Server it should create two new columns named as B.Ed and PTC and insert "1" in fields when they occur in Column1. This is how the Output should 输出量

I have a guess that it will be done with subqueries and I tried to understand them but couldn't understand the concept. So if you can help we with SQL query that can implement what I am trying to achieve here. Sorry about formatting but I hope you all are getting my point.

You can simply use case expression here:

select *, (case when ProfQual_16 = 'B.Ed' then 1 end) as BED,
          (case when ProfQual_16 = 'PTC' then 1 end) as PTC 
from table t;

You can update your existing table using the case expression

If you already have the new column in your existing table then you can directly use the update statement else you if you want you can add a new column as per your requirement.

ALTER TABLE EducationQualification
ADD BTech VARCHAR(127),MTech VARCHAR(127),

SQL Query: Since I created the new column during the creation of table:

CREATE TABLE EducationQualification
(
Qualification VARCHAR(100),
BTech   VARCHAR(100) NULL,
MTech   VARCHAR(100) NULL
)

INSERT INTO EducationQualification
(Qualification,BTech,MTech)
VALUES
('B.Tech',NULL,NULL),('B.Tech',NULL,NULL),('B.Tech',NULL,NULL),('M.Tech',NULL,NULL)

SELECT * FROM EducationQualification

Output:

在此处输入图片说明

UPDATE EducationQualification
SET BTech = CASE
                WHEN Qualification = 'B.Tech' THEN 1
                ELSE NULL
            END,
    MTech = CASE
                WHEN Qualification = 'M.Tech' THEN 1
                ELSE NULL
            END

Result After Update Query:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM