0
votes

I have some records.

 ID      Salary    WillGroupBy   Amount
 ----------------------------------------
 6320     100        1            15
 6320     150        1            20
 6694     200        0            25
 6694     300        0            30
 7620     400        1            45
 7620     500        1            50

How can I group by only which "WillGroupBy = 1" records?

(I will SUM Salary and Amount columns) I want to get this result:

 ID      Salary    WillGroupBy   Amount
 ----------------------------------------
 6320     250        1            35
 6694     200        0            25
 6694     300        0            30
 7620     900        1            95

Can you help me please :( ?


Solution:

SELECT ID, SUM(Salary) Salary, WillGroupBy, SUM(Amount) Amount
FROM YourTable
where WILLGROUPBY = 0
union all
SELECT ID, SUM(Salary) Salary, WillGroupBy, SUM(Amount) Amount
FROM YourTable
where WILLGROUPBY = 1
group by ID, WillGroupBy

I used this solution via Erhan.

I would to know that how it could be in another way.

1
Please tag your question with the database, e.g. mysql, sql-server, oracle, etc. - Barmar

1 Answers

0
votes

With MySQL you can do:

SELECT ID, SUM(Salary) Salary, WillGroupBy, SUM(Amount) Amount, @row := @row + 1
FROM YourTable
JOIN (SELECT @row := 0) v
GROUP BY ID, IF(WillGroupBy = 1, -1, @row)

DEMO