0
votes

The query statement I want is whether GROUP BY can be changed according to the value of the selected column.

For example, The query I was thinking of is as below,

SELECT DATE, A,B,C FROM TABLE
GROUP BY DATE
   CASE WHEN C ='1' THEN A,B
ELSE '2' THEN A END.

If C is 1, the final query is

SELECT DATE, A,B,C FROM TABLE
GROUP BY DATE, A, B

If C is 2, the final query is

SELECT DATE, A,B,C FROM TABLE
    GROUP BY DATE, A

The query is applied like this according to each C value, so the result I want is

DATE     A       B       C
----    ------------------
2022.01 A1       50      1
2022.01 A2       30      1
2022.02 (A1+A2)  80      2
2022.03 A1       10      1
2022.03 A2       20      1

want Can you make a sql query with this syntax?

To change and apply the columns grouped according to the C value.. ;(

1
For those of you who have missed the answer button, there is an answer button below. ;(choding
The query I was thinking of is as below There are no agregate functions - what is the reason for to use GROUP BY? If C is 2, the final query is IF different B exists in a group then what one value must be returned?Akina

1 Answers

0
votes

You might be able to get the result you want by combining the result of two queries using UNION ALL. The exact syntax may differ (sometimes you have to select from a subquery) and you may want to specify ordering but I think this could work.

SELECT DATE,A,B,C 
FROM TABLE
 WHERE C = '1'
 GROUP BY DATE,A,B
UNION ALL
SELECT DATE,A,B,C 
 FROM TABLE
 WHERE C = '2'
GROUP BY DATE,A;