Reputation: 19
How can I combine two queries? I am new to database. Both are working fine but combine both queries into a single query:
i need only one row with min value each column.. i used cast for two decimal needed.
SELECT
Date_Time,
CAST(Column1 AS decimal(10, 2)) AS Column1,
CAST(Column2 AS decimal(10, 2)) AS Column2,
STATUS
FROM Table
SELECT
MIN(Column1) AS Column1,
MIN(Column2) AS Column2
FROM Table
Upvotes: 0
Views: 77
Reputation: 1269463
If you want the minimum values as separate columns, you would just use window functions:
SELECT Date_Time,
CAST(Column1 AS decimal(10, 2)) AS Column1,
CAST(Column2 AS decimal(10, 2)) AS Column2,
STATUS ,
MIN(Column1) OVER () as min_column1,
MIN(Column2) OVER () as min_column2
FROM Table;
If you want the minimum values as an additional row, you would use UNION ALL
:
SELECT Date_Time,
CAST(Column1 AS decimal(10, 2)) AS Column1,
CAST(Column2 AS decimal(10, 2)) AS Column2,
STATUS
FROM Table
UNION ALL
SELECT NULL,
MIN(Column1) AS Column1,
MIN(Column2) AS Column2,
NULL
FROM Table;
Upvotes: 0
Reputation: 15893
I think you need to use window function to have all the rows from your first query along with two columns having minimum value for column1 and column 2 for each date_time and status.
SELECT
Date_Time,
CAST(Column1 AS decimal(10, 2)) AS Column1,
CAST(Column2 AS decimal(10, 2)) AS Column2,
STATUS ,
MIN(Column1)over(partition by date_time,status) AS MinColumn1,
MIN(Column2)over(partition by date_time,status) AS MinColumn2
FROM Table
It would be better if you share sample input and output.
Upvotes: 0
Reputation: 71159
Judging by your comments, it seems like you just need this:
SELECT
MIN(CAST(Column1 AS decimal(10, 2))) AS decimal_Column1,
MIN(CAST(Column2 AS decimal(10, 2))) AS decimal_Column2
FROM Table
Upvotes: 0
Reputation: 4935
If you want the minimum value for each date then you need to use group by
clause
SELECT
Date_Time,
MIN(Column1) as column1,
MIN(Column2) as column2,
MIN(CAST(Column1 AS decimal(10, 2))) AS decimal_Column1,
MIN(CAST(Column2 AS decimal(10, 2))) AS decimal_Column2
FROM Table
GROUP BY Date_Time
Upvotes: 0
Reputation: 1690
You can use Windows Functions
:
Select Date_Time,
CAST(Column1 as decimal(10,2)) As Column1,
CAST(Column2 as decimal(10,2)) As Column2 ,
STATUS,
Min(Column1 ) Over() as MinCol1,
Min(Column2) Over() as MinCol2
From Table
Upvotes: 1