I have to retrieve and sort data from a server. First of all, the query is too long and I think it could be shorter but I don't know how. Secondly, I get separate tables for each sensor type. But it would be better to have only one table in which there is a column for each sensor type. The difficulty is selecting the distinct top 4 of each sensor and sorting them according to the correct DateTime
.
SELECT TOP(2)
[clRegId] AS Id, [clRegDateTimestamp] AS DateTime,
([clRegSysNbr] + 1) AS CelNr,
((([clRegValue] - 4860.00)/20.00) - 30.00) AS Value,
CASE
WHEN clRegId = 0 THEN ''airTemp''
END AS Sensor
FROM
[Database].[dbo].[registrations]
WHERE
clRegSysNbr = 10
AND clRegId = 0
AND clRegMain = 3
AND clRegConfigId = 3
ORDER BY
DateTimestamp DESC
SELECT TOP(2)
[clRegId] AS Id, [clRegDateTimestamp] AS DateTime,
([clRegSysNbr] + 1) AS CelNr,
([clRegValue] / 40.0) AS Value,
CASE
WHEN clRegId = 1 THEN ''product cold''
END AS Sensor
FROM
[Database].[dbo].[registrations]
WHERE
clRegSysNbr = 10
AND clRegId = 1
AND clRegMain = 3
AND clRegConfigId = 3
ORDER BY
DateTimestamp DESC
This code returns the following separate tables as a result.
First table from the air sensor:
Id | DateTime | CelNr | Value | Sensor |
---|---|---|---|---|
0 | 7/11/2022 13:20:00 | 11 | -0,6 | air |
0 | 7/11/2022 13:15:00 | 11 | -0,5 | air |
Second table from the product cold sensor
Id | DateTime | CelNr | Value | Sensor |
---|---|---|---|---|
1 | 7/11/2022 13:20:00 | 11 | -0,8 | product cold |
1 | 7/11/2022 13:15:00 | 11 | -0,9 | product cold |
It would be better if it looked like this:
DateTime | CelNr | air | product cold |
---|---|---|---|
7/11/2022 13:20:00 | 11 | -0,6 | -0,8 |
7/11/2022 13:15:00 | 11 | -0,5 | -0,9 |
Is it possible with SQL to achieve this kind of a combined table as result?