Sql pivot without aggregate

While trying to expand the sql table, I came across this message here . Using this method, I created a query. However, I realized that it certainly combines the results with the MAX function. However, I need Colum to rotate, but for all the cases that need to be shown. Code taken from above.

  SELECT dy,
         MAX(CASE WHEN period = 1 THEN subj ELSE NULL END) AS P1,
         MAX(CASE WHEN period = 2 THEN subj ELSE NULL END) AS P2,    
    FROM Classes
GROUP BY dy

So, essentially, I want to use this, but without the maximum function? Any ideas?

Change example data

Day   Period    Subject

Mon   1         Ch
Mon   2         Ph
Tue   1         Ph
Tue   2         Ele
Mon   1         Ch
Mon   2         Ph
Tue   1         Ph
Tue   2         Ele

Output example

Day   P1   P2   

Mon   Ch   Ph   
Mon   Ch   Ph   
Tue   Ph   Ele  
Tue   Ph   Ele  

so if data is entered twice, it appears twice ...

Change actual sql ..

  SELECT other
         MAX(CASE WHEN period = 1 THEN table2.subj ELSE NULL END) AS P1,
         MAX(CASE WHEN period = 2 THEN table2.subj ELSE NULL END) AS P2    
    FROM table1
left join table2 on table2.ID = subject

GROUP BY other

Data examples

Table 1

Dy   Period    Subject other

Mon   1         1       1
Mon   2         2       1
Tue   1         3       2
Tue   2         4       2
Mon   1         5       3
Mon   2         6       3
Tue   1         7       4
Tue   2         8       4

table 2

ID  Subj
1 ch
2 ph
3 ph
4 ele
5 ch
6 ph
7 ph
8 Ele

Output example

Day   P1   P2   other

Mon   Ch   Ph   1
Mon   Ch   Ph   3
Tue   Ph   Ele  2
Tue   Ph   Ele  4
+3
source share
3 answers

. Mth, CS2, Lab Hu ? .

, , , () Mon, , (StudentID) SELECT GROUP BY. MAX ( ), , , .

SQL :

SELECT student_id, dy,
     MAX(CASE WHEN period = 1 THEN subj ELSE NULL END) AS P1,
     MAX(CASE WHEN period = 2 THEN subj ELSE NULL END) AS P2,    
FROM Classes
GROUP BY student_id, dy

. , , , _id dy SELECT GROUP BY.

0

.

SELECT dy,        CASE WHEN period = 1 THEN subj ELSE NULL END AS P1,        CASE WHEN period = 2 THEN subj ELSE NULL END AS P2
  FROM Classes

0

, MAX(), . , , GROUP BY, .

For example, if it dyis unique, you will get all the results, but if you have another column that makes your proposal GROUP BYunique, you can simply add it and you will get all the results. Say the column is called `id ':

  SELECT dy,id,
         MAX(CASE WHEN period = 1 THEN subj ELSE NULL END) AS P1,
         MAX(CASE WHEN period = 2 THEN subj ELSE NULL END) AS P2,    
    FROM Classes
GROUP BY dy, id
0
source

Source: https://habr.com/ru/post/1771081/


All Articles