I am facing one issue in my following Mysql query. I have a table with columns id, pid, state, price1, discount, tot4
and tech1
. I try to get a group by sum where pid is same and state value is 11 and 12.
But the issue which I am facing is that current query sums every entry where pid is same an state is anything. I want it should only sum where state is 11 and 12.
SELECT
id, pid, state,
SUM(CASE WHEN state in (11, 12) THEN price1 ELSE price1 END) as price1,
SUM(CASE WHEN state in (11, 12) THEN discount ELSE discount END) as discount ,
SUM(CASE WHEN state in (11, 12) THEN tot4 ELSE tot4 END) as tot4 ,
tech1
FROM
iap4
GROUP BY
pid;
2
Answers
Based on this ‘I try to get a group by sum where pid is same and state value is 11 and 12.‘
If you need to filter to certain states, then sql provides the ‘where’ condition to achieve this:
If you want the state level view also in the grouping:
You can use ‘sum(case when …)’ but this will be less efficient. Note the correct line should be:
if you put price1 after the ‘ELSE’ then you will sum price1 when the condition is both true and false.
It looks like you want to sum the columns
price1
,discount
, andtot4
only when thestate
is 11 or 12, and group the results bypid
. Looking at your query, I think you are summing these columns regardless of thestate
value. Which is in return giving you the sum of allstate
.I did change the
SUM
functions to only considerprice1
,discount
, andtot4
whenstate
is 11 or 12. And theWHERE
clause filters out the rows withstate
11 or 12 before performing the grouping.Modify the query after you understand the issue according to your requirements.