Question:
How SQL select first row and second row from a field and appear in two columns?
macausite
2012-02-20 10:03:28 UTC
How SQL select first row and second row from a field and appear in two columns?

For example:
-----------
| Row1 |
-----------
| Row2 |
-----------

To
--------------------
Row1 | Row2
--------------------
Four answers:
AJ
2012-02-20 12:07:35 UTC
Use PIVOT
DC2000
2012-02-20 11:16:33 UTC
Are you talking about taking the results set from a SELECT query and using the rows as columns? If so, you can't do that.
TheMadProfessor
2012-02-20 12:43:33 UTC
As previously mentioned, PIVOT is one (and probably the preferable) way. If your particular DBMS doesn't support PIVOT, about the only other way I can think of is by using selfjoins or a UNION. For example:



SELECT a.custID AS Customer, COALESCE(b.totPay, 0) AS "January Payments",

COALESCE(c.totPay, 0) AS "February Payments", ... FROM

(SELECT custID FROM customer) a

LEFT OUTER JOIN

(SELECT custID, SUM(paymentAmount) AS totPay FROM payments

WHERE MONTH(paymentDate) = 1 GROUP BY custID) b

ON a.custID = b.custID

LEFT OUTER JOIN

...

LEFT OUTER JOIN

(SELECT custID, SUM(paymentAmount) AS totPay FROM payments

WHERE MONTH(paymentDate) = 12 GROUP BY custID) m

ON a.custID = m.custID



SELECT custID AS Customer, SUM(janPay) AS "January Payments",

SUM(febPay) AS "February Payments", ... FROM

(SELECT custID, SUM(paymentAmount) AS janPay), 0 AS febPay, 0 AS marPay, ...

FROM payments WHERE MONTH(paymentDate) = 1 GROUP BY custID)

UNION

(SELECT custID, 0, SUM(paymentAmount), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

FROM payments WHERE MONTH(paymentDate) = 2 GROUP BY custID)

UNION

...

UNION

(SELECT custID, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SUM(paymentAmount),

FROM payments WHERE MONTH(paymentDate) = 12 GROUP BY custID)

GROUP BY custID
?
2016-10-13 15:00:17 UTC
attempt this: go with call, Org identity, digital mail, Designation, (go with t1.digital mail from user_table t1 the place t1.[Org identity] = t2.[Org identity] and t1.Designation = 'Engineer') as New from user_table t2


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...