Home > database > SQL is a field is equal to a specific value, another field summation
SQL is a field is equal to a specific value, another field summation
Time:12-23
My SQL level co., LTD., recently need to query the database, but I tried many methods, or can not get the desired results, for everyone here, I have a query table X, content is as follows: ID NAME CLASS AREA 0001 A1 100 0002 A2 200 0003 c A1 100 0004 B1 400 0005 c B2 300
At the same time I want to be in the NAME, if exist A1 and A2, A1 is preserved, to add summary AREA at the same time, the results are as follows: ID NAME CLASS AREA 0001 A1 300 0003 c A1 100 0004 B1 400 0005 c B2 300
CodePudding user response:
The CREATE TABLE # A ( ID VARCHAR (20), The NAME VARCHAR (20), CLASS a VARCHAR (20), AREA INT ) # INSERT INTO A VALUES (' 0001 ', 'A', 'A1, 100) # INSERT INTO A VALUES (' 0002 ', 'A', 'A2' 200) # INSERT INTO A VALUES (' 0003 ', 'c', 'A1, 100) # INSERT INTO A VALUES (' 0004 ', 'has',' B1, 400) # INSERT INTO A VALUES (' 0005 ', 'c', 'B2, 300)
SELECT Anderson D, A.N AME, A.C LASS, A.A REA + ISNULL ((SELECT B.A REA # FROM A to B WHERE biggest LASS='A2' AND B.N AME=A.N AME), 0) FROM # aa WHERE A.C LASS! ='A2' DROP TABLE # A
CodePudding user response:
- gather together a jollification
Select ID, NAME, case CLASS when 'A3' then 'A1 else CLASS end the CLASS, the sum (area) The from x Group by ID NAME, case CLASS when 'A3' then 'A1 else CLASS end
CodePudding user response:
The CREATE TABLE # T ( ID VARCHAR (10), the NAME VARCHAR (10), a CLASS a VARCHAR (10), AREA INT )
INSERT INTO # t VALUES (' 0001 ', 'a', 'A1, 100) INSERT INTO # t VALUES (' 0002 ', 'a', 'A2' 200) INSERT INTO # t VALUES (' 0003 ', 'c', 'A1, 100) INSERT INTO # t VALUES (' 0004 ', 'has',' B1, 400) INSERT INTO # t VALUES (' 0005 ', 'c', 'B2, 300) INSERT INTO # t VALUES (' 0006 ', 'd', 'A2' 700)
The SELECT MIN (id) AS id, name, CLASS, the SUM (AREA) AS AREA FROM ( SELECT ID, NAME, AREA, and the CASE WHEN the CLASS IN (' A1 ', 'A2') THEN 'A1 ELSE CLASS END AS a CLASS FROM # T ) a GROUP BY name, the CLASS The ORDER BY id