I've done a query like this :
SELECT Code, kind, SUM(valP) AS value FROM transaction WHERE tp = 'N' and date = '20110312' GROUP BY Code,kind ORDER BY Code,kind;
on a database table that give me this resultset :
+------+------+------+
| Code | kind| value|
+------+------+------+
| 1 | TR | 25,99|
| 1 | CT | 22,17|
| 2 | TR | 14,23|
| 3 | DD | 09,67|
| 3 | DD | 23,87|
| 3 | CT | 34,87|
+------+------+------+
The code represent a transaction code, kind represent payments type, and value represent the value of the payments.
I want to inclue in the result set only the grouped result that contain a kind type = 'CT' but i want to include also the other payments kind in the same transaction, for example i've tried by adding an having to the upper query:
SELECT Code, kind, SUM(valP) AS value FROM transaction WHERE tp = 'N' and date = '20110312' GROUP BY Code,kind HAVING kind = 'CT' ORDER BY Code,kind;
but i obtain something like this :
+------+------+------+
| Code | kind| value|
+------+------+------+
| 1 | CT | 22,17|
| 3 | CT | 34,87|
+------+------+------+
instead i want to retrieve something like this :
+------+------+------+
| Code | kind| value|
+------+------+------+
| 1 | TR | 25,99|
| 1 | CT | 22,17|
| 3 | DD | 09,67|
| 3 | DD | 23,87|
| 3 | CT | 34,87|
+------+------+------+
All lines of the transaction that have within a record with type CT , is there a way to obtain this ?
How can i do ?
I'm actually working on a SQL Server 2005 but i may need run a similar query in PostgreSQL.
Thanks
You can add condition that tells "This Code must have a row with CT" sa do a sub-query:
SELECT Code FROM transaction WHERE kind='CT' GROUP BY Code ;
And to your first query add a filter to show only those records which have Code in previous subquery:
... AND Code IN (SELECT Code FROM transaction WHERE kind='CT' GROUP BY Code ) ...
This will get rid of record Code 2, because 2 will no be in results from first query
This should do it:
SELECT Code, kind, SUM(valP) AS value FROM transaction WHERE tp = 'N' AND date = '20110312' AND code IN (SELECT t2.code FROM transaction t2 WHERE t2.kind = 'CT') GROUP BY Code,kind ORDER BY Code,kind;
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.