How can I align the rows and attributes of each field in a table to appear in the same line, using the given table as an example?. Mark this all fields in this table are varchar so as to enable uniformity.
| STD | SUBJECT | MARKS | COMMENT | TDATE |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| ST1 | MATH | 25% | POOR | 1/02/2021 |
| ST1 | ENGLISH | 88% | DIST | 2/02/2021 |
| ST1 | SCIENCE | 56% | PASS | 4/02/2021 |
The table should appear like this after unpivoting the contents in [Subject]
:
STD | MATH | COMMENT | TDATE | ENGLISH | COMMENT | TDATE | SCIENCE | COMMENT | TDATE |
---|---|---|---|---|---|---|---|---|---|
ST1 | 25% | POOR | 1/02/2021 | 88% | DIST | 2/02/2021 | 56% | PASS | 4/02/2021 |
I tried with my code and got lots of errors, so maybe I could get some help to achieve the desired result.
SELECT
[MATH],
[ENGLISH],
[SCIENCE]
FROM (
SELECT
STD, stdn,
cont,
x,
SUBJECT
FROM
[dbo].[Exam]
UNPIVOT (
x
for cont in (COMMENT, TDATE)
) a
) a
PIVOT (
MAX(x)
FOR SUBJECT IN (
[MATH],
[ENGLISH],
[SCIENCE],
)
) p
WHERE p.stdn IN (SELECT STD FROM [dbo].[exam])
2条答案
按热度按时间jtjikinw1#
i think i solved it when i used MAX(CASE)
ql3eal8s2#
Pivots for presentation purposes are not well suited to SQL and often better performed by a "front end" or "reporting tool" despite this, it is possible to pivot this data using T-SQL.
I assume that an unstated requirement is that the columns are presented in a specific left-to-right "block sequence" of "subject-mark-comment-tdate" so there needs to be a way to organize the columns in that sequence. A further probable requirement is that the pivot cater for an unknown number of total columns, for this you need "dynamic sql".
Note: This "unpivot" is complicated by the fact that there are different data types involved, one way to avoid this is to cast all data to strings or
sql_variant
(which is the approach seen below). Another (that I prefer) is to use JSON explained here but I wasn't also able to control the the "rnk" value as I needed for this query to formulate the numeric sequence of columns.So, this is proposed:
see this as a working demo
nb: As I ended up converting the date column into a string to control the format, you could replace the "as sql_variant" with "as varchar(100)"(length of 100 is a guess)