SQL Query and Sort From Multiple Tables - sql

Working with SQL via a NOVA Oracle DB. Need to know how to query from multiple tables and arrange results based on being sorted by the highest values. Here are a few lines of code to reflect the three tables:
INSERT INTO VEHICLES
(vehicleVIN,vehicleType,vehicleMake,vehicleModel,vehicleWhereFrom,vehicleWholesaleCost,vehicleTradeID)
VALUES
('147258HHE91K3RT','compact','chevrolet','spark','Maryland',20583.00,NULL);
INSERT INTO VEHICLES
(vehicleVIN,vehicleType,vehicleMake,vehicleModel,vehicleWhereFrom,vehicleWholesaleCost,vehicleTradeID)
VALUES
('789456ERT0923RFB6','Midsize','ford','Taurus','washington, d.c.',25897.22,1);
INSERT INTO VEHICLES
(vehicleVIN,vehicleType,vehicleMake,vehicleModel,vehicleWhereFrom,vehicleWholesaleCost,vehicleTradeID)
VALUES
('1234567890QWERTYUIOP','fullsize','Lincoln','towncar','Virginia',44222.10,NULL);
AND
INSERT INTO SALES
(saleID,grossSalePrice,vehicleStatus,saleDate,saleMileage,customerID,salespersonID,vehicleVIN)
VALUES
(1,25987.28,'sold',date '2012-10-15',10,1,1,'147258HHE91K3RT');
INSERT INTO SALES
(saleID,grossSalePrice,vehicleStatus,saleDate,saleMileage,customerID,salespersonID,vehicleVIN)
VALUES
(2,29999.99,'sold',date '2012-10-17',50087,2,2,'789456ERT0923RFB6');
INSERT INTO SALES
(saleID,grossSalePrice,vehicleStatus,saleDate,saleMileage,customerID,salespersonID,vehicleVIN)
VALUES
(3,47490.88,'sold',date '2012-11-05',30,3,3,'1234567890QWERTYUIOP');
AND
INSERT INTO CUSTOMERS
(customerID,customerFirName,customerLasName,customerMiName,customerStreet,customerState,customerCity,customerZip)
VALUES
(1,'Regorna','Trasper','J','11111 Address Way','Maryland','Hollywood','20636');
INSERT INTO CUSTOMERS
(customerID,customerFirName,customerLasName,customerMiName,customerStreet,customerState,customerCity,customerZip)
VALUES
(2,'Bob','Seagram','A','22222 Seagram Lane','Texas','Houston','77001');
INSERT INTO CUSTOMERS
(customerID,customerFirName,customerLasName,customerMiName,customerStreet,customerState,customerCity,customerZip)
VALUES
(3,'Sally','Anderson','P','33333 Pheonix Drive','Arizona','Pheonix','85001');
Obviously there are other tables that come into play here (salesperson, etc.), however these are the only tables needed for the query. The query I want to pull needs to show the total count of sales for each model, sorted by the highest values, and the total count of sales for each zip code, sorted by the highest values. An example (using the data provided above) would look similar to this:
MODEL NUMBER of SALES ZIP CODE NUMBER OF SALES
spark 1 20636 1
Taurus 1 77001 1
towncar 1 85001 1
The results need to be sorted by highest values, based on the number of sales. I'm also trying to accomplish this via a single SELECT query.
I've tried some ideas, but haven't been able to find anything that hits the home run yet. Thanks for the help!

See if this is what you're after:
SELECT DISTINCT v.VEHICLEMODEL, COUNT(*) OVER (PARTITION BY s.VEHICLEVIN) "CAR_SALES"
, c.CUSTOMERZIP, COUNT(*) OVER (PARTITION BY c.CUSTOMERZIP )"TOTAL_SALES_AT_ZIP"
FROM SALES s, VEHICLES v, CUSTOMERS c
WHERE s. VEHICLEVIN = v. VEHICLEVIN
and c. CUSTOMERID = s. CUSTOMERID
ORDER BY 2 DESC , 4 DESC

Related

Multiple SELECT followed by multiple UPDATE

I have two tables - 1st table gas_emissions, 2nd table - regiony_avg.
Table gas_emissions has columns region, region_id, data_val, year.
Table regiony_avg has columns region_id, avg_region.
There are multiple values for each region because they're calculated every year. I need to calculate AVG for each region and insert it into regiony_avg.
There are over 10 regions, what I've done is
SELECT AVG(data_val) AS AKL
FROM gas_emissions
WHERE region_id = 'AKL'
and then
UPDATE regiony_avg
SET avg_region = 1999.64771428571
WHERE region_id = 'AKL'
I did it for each of regions. However I can't see how to do it if there are for example 1000 regions. Is there any way to get AVG for all unique regions at and then insert it into regiony_avg at once?
I think you just want insert . . . select:
insert into regiony_avg (region_id, avg_region)
selet region_id, avg(data_val)
from gas_emissions
group by region_id;
Note: I see little reason to store this information in a table when it can easily be calculated using an aggregation query. In fact, you can add the average to each row of the original table using window functions:
select ge.*,
avg(data) over (partition by region_id) as region_avg
from gas_emissions ge;

How Do I Count Occurrences in a Column in SQL?

I have a table that lists the following values. Some of the values in column 1 show up twice for the same customer (for example apple could show up 2 or more times.)
Column 1
Apples
Oranges
Bananas
I know I can use this to get the count for each of the values.
SELECT column 1, COUNT(*)
FROM table
GROUP BY column 1
Is there a way to write a SQL statement that looks at when the count of one of those values shows up twice for the same customer?
For example, I want to find out how many times apple shows up twice for the same customer.
Assuming you have a customer column, your query could look like this:
SELECT customer, column1, COUNT(*)
FROM table
GROUP BY customer, column1
HAVING COUNT(*) > 1;
This will show you a customer field, and your column1 (the column with Apple and Banana and so on), and the number of times the combination of these fields occur.
The GROUP BY will ensure that the count is calculated correctly.
The HAVING will only show records where the COUNT value is > 1 after the grouping has occurred.

Exclude a duplicate record from a view based on condtions and keep 1 - SQL Server 2012

I have three joined tables Student, StudentTransportOrder and Transport in SQL Server 2012.
I have created a StudentActivity view for this.
In the StudentTransportOrder table, each student record has a unique TransportOrderID.
When transport is ordered, VehicleID this is recorded into the StudentTransportOrder table.
Unfortunately the same VehicleID has been entered for the same date and time for a student records.
The StudentActivity view already returns records based on where conditions, but I also need to remove the duplicate records, preferably keep the records where if a student has used transport on the same date and time, that only one distinct VehicleID is returned and preferably the where the transport type is TransportVehicle = Car
How can I amend the view , without deleting records from the main tables, also bring back records even if no transport has been ordered
Please help
Append
ROW_NUMBER() OVER(PARTITION BY StudentID,VehicleID ORDER BY (SELECT NULL)) AS PartitionedCount
... to your query and use a filter like WHERE PartitionedCount=1.
This will number your rows for each combination of Student and vehicle separately (you'll have to include the date or datetime probably).
You can use the (ORDER BY (SELECT NULL)) to force a car sorted on top...
UPDATE
As I do not know your actual tables here's a general example:
DECLARE #tbl TABLE(ID INT IDENTITY,GroupID INT,SomeValue VARCHAR(100));
INSERT INTO #tbl(GroupID,SomeValue) VALUES
(1,'val 1 for 1')
,(1,'val 2 for 1')
,(1,'val 3 for 1')
,(2,'val 1 for 2')
,(2,'val 2 for 2')
,(3,'val 1 for 3')
,(3,'val 2 for 3');
WITH Numbered AS
(
SELECT tbl.*
,ROW_NUMBER() OVER(PARTITION BY GroupID ORDER BY ID /*DESC*/) AS Number
FROM #tbl AS tbl
)
SELECT * FROM Numbered
WHERE Number=1
Try first without the WHERE. You will get all rows with partitioned numbering. Using the WHERE will reduce the output to the one with number =1.
It is on you to find a clever ORDER BY which brings your cars to the top (CASE will help you probably).
Just good to know: In my ORDER BY you find an inactive DESC. If you take away the /**/ you can use the same approach to find the last row to a given sort order.

SQL server insert same value to multiple rows

How can I insert the same value to multiple rows?
For example, I want to insert $10 dollars to all customers bill table Bill_Amount column where customer is equal to specific service type
I want to do it in SQL Server.
Assuming you have a customers table, you could use the insert-select syntax and select a literal of 10$:
INSERT INTO bill_amount (customer_id, bill_amount)
SELECT customer_id, 10
FROM customers
WHERE service_type = 'some_service'

SQL - Insert using Column based on SELECT result

I currently have a table called tempHouses that looks like:
avgprice | dates | city
dates are stored as yyyy-mm-dd
However I need to move the records from that table into a table called houses that looks like:
city | year2002 | year2003 | year2004 | year2005 | year2006
The information in tempHouses contains average house prices from 1995 - 2014.
I know I can use SUBSTRING to get the year from the dates:
SUBSTRING(dates, 0, 4)
So basically for each city in tempHouses.city I need to get the the average house price from the above years into one record.
Any ideas on how I would go about doing this?
This is an SQL Server approach, and a PIVOT may be a better, but here's one way:
SELECT City,
AVG(year2002) AS year2002,
AVG(year2003) AS year2003,
AVG(year2004) AS year2004
FROM (
SELECT City,
CASE WHEN Dates BETWEEN '2002-01-01T00:00:00' AND '2002-12-31T23:59:59' THEN avgprice
ELSE 0
END AS year2002,
CASE WHEN Dates BETWEEN '2003-01-01T00:00:00' AND '2003-12-31T23:59:59' THEN avgprice
ELSE 0
END AS year2003
CASE WHEN Dates BETWEEN '2004-01-01T00:00:00' AND '2004-12-31T23:59:59' THEN avgprice
ELSE 0
END AS year2004
-- Repeat for each year
)
GROUP BY City
The inner query gets the data into the correct format for each record (City, year2002, year2003, year2004), whilst the outer query gets the average for each City.
There many be many ways to do this, and performance may be the deciding factor on which one to choose.
The best way would be to use a script to perform the query execution for you because you will need to run it multiple times and you extract the data based on year. Make sure that the only required columns are city & row id:
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
INSERT INTO <table> (city) VALUES SELECT DISTINCT `city` from <old_table>;
Then for each city extract the average values, insert them into a temporary table and then insert into the main table.
SELECT avg(price), substring(dates, 0, 4) dates from <old_table> GROUP BY dates;
Otherwise you're looking at a combination query using joins and potentially unions to extrapolate the data. Because you're flattening the table into a single row per city it's going to be a little tough to do. You should create indexes first on the date column if you don't want the database query to fail with memory limits or just take a very long time to execute.