select max, min values from two tables - sql

I have two tables. Differ in that an archive is a table and the other holds the current record. These are the tables recording sales in the company. In both we have among other fields: id, name, price of sale. I need to select from both tables, the highest and lowest price for a given name. I tried to do with the query:
select name, max (price_of_sale), min (price_of_sale)
from wapzby
union
select name, max (price_of_sale), min (price_of_sale)
from wpzby
order by name
but such an inquiry draws me two records - one of the current table, one table archival. I want to chose a name for the smallest and the largest price immediately from both tables. How do I get this query?

Here's two options (MSSql compliant)
Note: UNION ALL will combine the sets without eliminating duplicates. That's a much simpler behavior than UNION.
SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
FROM
(
SELECT Name, Price_Of_Sale
FROM wapzby
UNION ALL
SELECT Name, Price_Of_Sale
FROM wpzby
) as subQuery
GROUP BY Name
ORDER BY Name
This one figures out the max and min from each table before combining the set - it may be more performant to do it this way.
SELECT Name, MAX(MaxPrice) as MaxPrice, MIN(MinPrice) as MinPrice
FROM
(
SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
FROM wapzby
GROUP BY Name
UNION ALL
SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
FROM wpzby
GROUP BY Name
) as subQuery
GROUP BY Name
ORDER BY Name

In SQL Server you could use a subquery:
SELECT [name],
MAX([price_of_sale]) AS [MAX price_of_sale],
MIN([price_of_sale]) AS [MIN price_of_sale]
FROM (
SELECT [name],
[price_of_sale]
FROM [dbo].[wapzby]
UNION
SELECT [name],
[price_of_sale]
FROM [dbo].[wpzby]
) u
GROUP BY [name]
ORDER BY [name]

Is this more like what you want?
SELECT
a.name,
MAX (a.price_of_sale),
MIN (a.price_of_sale) ,
b.name,
MAX (b.price_of_sale),
MIN (b.price_of_sale)
FROM
wapzby a,
wpzby b
ORDER BY
a.name
It's untested but should return all your records on one row without the need for a union

SELECT MAX(value) FROM tabl1 UNION SELECT MAX(value) FROM tabl2;
SELECT MIN(value) FROM tabl1 UNION SELECT MIN(value) FROM tabl2;

SELECT (SELECT MAX(value) FROM table1 WHERE trn_type='CSL' and till='TILL01') as summ, (SELECT MAX(value) FROM table2WHERE trn_type='CSL' and till='TILL01') as summ_hist

Related

Union two tables with different column names

code snippet
As you can see from the results table, the union hasn't worked properly as there is more than one row for each make of car e.g. Toyota is listed for NG and KE in row 1 and for SA in row 3. Does anyone know how to join these tables more successfully?
Thank you!
How about making your last query another CTE, then grouping and summing the cnt on the new CTE?
WITH combined AS (
select title FROM autochek_ng
union all
select title FROM autocheck_kenya)
, brands AS (
SELECT LEFT(title, CHARINDEX(' ' , title)) as brand
FROM combined )
, aggregate as (
select brand, count(brand) as cnt
from brands
group by brand
UNION ALL
select make as brand, count(make) as cnt
from south_africa5000
group by make)
select brand, sum(cnt) cnt
from aggregate
group by brand

How to count the number of records in an sql database

I am using the below query to get distinct records from 4 specific columns in an sql DB.
SELECT DISTINCT customer,
product,
category,
sector
FROM data_table
I need to add the count of products in this query. Any ideas?
are you find something below
select count(*) from
(SELECT DISTINCT customer, product, category, sector
FROM data_table
) a
or do you need window function count() if your dbms support
SELECT DISTINCT customer, product, category, sector,
count(*) over() as cnt
FROM data_table

Avg Sql Query Always Returns int

I have one column for Farmer Names and one column for Town Names in my table TRY.
I want to find Average_Number_Of_Farmers_In_Each_Town.
Select TownName ,AVG(num)
FROM(Select TownName,Count(*) as num From try Group by TownName) a
group by TownName;
But this query always returns int values. How can i get values in float too?
;WITH [TRY]([Farmer Name], [Town Name])
AS
(
SELECT N'Johny', N'Bucharest' UNION ALL
SELECT N'Miky', N'Bucharest' UNION ALL
SELECT N'Kinky', N'Ploiesti'
)
SELECT AVG(src.Cnt) AS Average
FROM
(
SELECT COUNT(*)*1.00 AS Cnt
FROM [TRY]
GROUP BY [TRY].[Town Name]
) src
Results:
Average
--------
1.500000
Without ... *1.00 the result will be (!) 1 (AVG(INT 2 , INT 1) -truncated-> INT 1, see section Return types).
Your query is always returning int logically because the average is not doing anything. Both the inner and the outer queries are grouping by town name -- so there is one value for each average, and that average is the count.
If you are looking for the overall average, then something like:
Select AVG(cast(cnt as float))
FROM (Select TownName, Count(*) as cnt
From try
Group by TownName
) t
You can also do this without the subquery as:
select cast(count(*) as float) /count(distinct TownName)
from try;
EDIT:
The assumption was that each farmer in the town has one row in try. Are you just trying to count the number of distinct farmers in each town? Assuming you have a field like FarmerName that identifies a given farmer, that would be:
select TownName, count(distinct FarmerName)
from try
group by TownName;

Aggregate SQL Function to grab only one from each grouping

I have a table that I need to normalize with many fields In SQL-Server 2000.
It contains 2 fields which I'm using to come up with distinct combination as defined by the specs.
ID and Rate: there are multiple rows of same IDs and Rates
I first created a temp table by grouping the IDs and Rates combination.
SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total
INTO #Temp
GROUP BY ID
Now I use Distinct to find only the unique combinations. So i'll have multiple ID groups sharing same Total and IDCounts
SELECT DISTINCT Total, IDCounts
INTO #uniques
FROM #Temp
Now my question is how to join a single ID back to that distinct grouping of IDCounts and Total and put that into a new table? It doesn't matter which one of the IDs in the groups as long as I use one from the same grouping.
Keeping your temp tables (although this could all be done in a single query):
SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total
INTO #Temp
GROUP BY ID
SELECT Total, IDCounts, MIN(ID) AS SomeID
INTO #uniques
FROM #Temp
GROUP BY Total, IDCounts
Add "Min(ID) AS FirstID" to the select into #uniques.
Try something like this:
SELECT MAX(ID) AS Id, Count(*) AS IDCounts, SUM(RATE) As Total
FROM SOMETABLE
GROUP BY IDCounts, Total

How to put the Order BY in SQL UNION so TOTALS will show up always as last row?

I have SQL UNION where second part of that statement is the row that represents TOTALS. How can I ORDER BY where TOTALS will ALWAYS will show up as the last row?
Add an extra column to the queries being UNIONed, and make that column the first column in your ORDER BY clause.
So if I started with something like this:
SELECT product, price
FROM table
UNION
SELECT 'Total' AS product, SUM(price)
FROM table
I'd add a new column like this:
SELECT product, price
FROM (
SELECT product, price, 0 AS union_order
FROM table
UNION
SELECT 'Total' AS product, SUM(price), 1 AS union_order
FROM table
)
ORDER BY union_order
That way, regular products appear first, then the total appears at the end.
Have you tried using GROUP BY ROLLUP - it might be just want you want, although it's difficult to tell when you haven't posted your query.
You could try adding an 'order' column to each query and then order by that column...
SELECT x.*
FROM
(
SELECT columns, 2 AS [Order]
UNION
SELECT totals, 1 AS [Order]
) x
ORDER BY x.[Order]
select * from
(
select 1 as prio
, col1
, col2
...
from tableA
union
select 2 as prio
, totalCol1
, totalCol2
...
from tableB
) order by prio