1

I have a table (see the image below --red box). It describes the content of my table (A, B, C, and D) are the columns. The data structure will always be like this, if col A is Type_1, only col B has a content while if Col A is Type_2, Col C and D has contents while col B is NULL.

Now, the table which re enclosed with green box is my desired output.

enter image description here

My experience on building a select statement is not very extensive and I'm almost leaning towards creating two separate tables to get my desired result (like 1 table for Type_1 data only and another table for Type_2 data only).

Question is, is it possible to query two rows and combine it to become a single output result using SELECT query? Considering that these two rows are on the same table?

Thanks.

7
  • 3
    If there were multiple Type_1 and multiple Type_2 rows, how would it know which ones to combine? Commented May 19, 2014 at 12:54
  • @JoachimIsaksson, The data structure will always be like this Commented May 19, 2014 at 12:58
  • I apologize, I realized after the first comment that my image was not very clear. Please see the updated topic. Commented May 19, 2014 at 12:59
  • @HamletHakobyan The data structure is the same, but data may not be. Commented May 19, 2014 at 13:00
  • @AlexandreP.Levasseur, I told exactly about data structure. Commented May 19, 2014 at 13:01

3 Answers 3

4

Something like this:

SELECT
  Table2Id,
  MAX(B) B,
  MAX(C) C,
  MAX(D) D
FROM tbl
WHERE A != 'Type_3'
GROUP BY Table2Id
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming that there is only one row of data for type1 and one row of data for type 2, you can use the following:

 SELECT Id, MAX(B) AS B, MAX(C) AS C, MAX(D) AS D
   FROM Table2
  WHERE A IN ('Type_1','Type_2')
  GROUP BY Id

Example in this SQL Fiddle

Comments

0

You can make subqueries by enclosing them in parenthesis. As in:

SELECT (SELECT TOP 1 B FROM table ORDER BY some_ordering), (SELECT TOP 1 C FROM table WHERE NOT C IS NULL), D FROM table

The queries inside the parenthesis can apply to any table, and can use the data from the main query in calculations of the selected values and in filters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.