SQL, Select from table A and use result ID to loop though table B? - sql

I have a windows server running MS-SQL 2008.
I have a customer table that I need to select the id's of all customers that are Active, On Hold, or Suspended.
get all customers that are Y= current active customer H=on hold S=Suspended
select id from customer where active = 'Y';
the above statement worked fine for selecting the ID's of the affected customers.
I need to use these results to loop though the following command in order to find out what rates all the affected customers have.
get all rates for a customer
select rgid from custrate where custid = [loop though changing this id with results from first statement];
the id from the customer table coincides with the custid from the custrate table.
So in the end I need a list of all affected customer id's and what rgid's(rate group(s)) they have.

SQL isn't about loops in general and instead you should think in terms of joins.
select customer.id, custrate.rgid, customer.active
from customer
inner join custrate
on customer.id = custrate.custid
where active in ('Y', 'H', 'S")
order by customer.active, customer.id
would be a starting point to think about. However, that is just a wild guess as the schema was not specified nor the relations between the tables.

Related

How to get two fields based off a most recent date attribute?

I have two tables:
A Billing table, and a Customer table.
The Billing table and customer table both share a common attribute of Customer Number.
Billing Table
I'm trying to create a view that will retrieve the customer code and bill number for the most recent invoice date. I'm having trouble ordering my query.
This is what I have so far.
CREATE VIEW RECENT_ORDER
AS
SELECT
c.Customer_Num, b.Bill_Num
FROM CUSTOMER c
INNER JOIN BILLING b ON c.Customer_Num = b.Customer_Num
WHERE c.Fname='Jess' AND c.Lname='Hanks'
HAVING MAX(b.Bill_Date);
I have also tried putting the 'HAVING' portion as a WHERE statement.
This should get your answer:
CREATE VIEW RECENT_ORDER
AS
SELECT c.customer_num, b.bill_num
FROM customer c
JOIN billing b ON c.customer_num = b.customer_num
WHERE b.bill_date =
(SELECT MAX(bill_date) FROM billing WHERE customer_num = b.customer_num)
AND c.Fname='Jess' AND c.Lname='Hanks'
Though normally I wouldn't expect to create a view that limits results to just one customer!? Remove the last line AND c.Fname ... if you intend to get the most recent result for any/all customers. Note that you may get multiple results for a customer if they have more than one invoice on the same date.

Why do repeated values appear in SQL results

I'm with a doubt about joins. For example, using an example database dvdrental, this query:
SELECT customer.customer_id
, first_name
, last_name
FROM customer
INNER JOIN payment ON Customer.customer_id = Payment.customer_id
Some records appear repeated, for example, it appears 3 times "342 Harold Martino" like:
342 Harold Martino
342 Harold Martino
342 Harold Martino
Do you know why it appears repeated records like in this example that appears the same Record 3 times? This repetition means that there are 3 records in the payment table where customer_id = 342? But this query "select * from payment where customer_id = 342" returns 32 records. So I'm not understanding properly how the join works.
There are many resources around this, so to be short your expression says this in plain english:
Get all the records from the customer table
Then for each of those records, get every payment record that has the same value in the customer_Id field.
return a single row for each payment record that duplicates all the fields from the customer record for each row in the payment record.
Finally, only return 3 columns:
the customer_id column from the customer table
the first_name column that is in one of the customer or payment table
the last_name column that is in one of the customer or payment table
Note that we didn't bring back any columns from the payment table... (I assume first_name and last_name are fields in the customer table...)
Keep in mind, a CROSS JOIN (or a FULL OUTER JOIN) is a join that says take all fields from the left side and create a single row combination that is multiplied by the right side, so for every row on the left, return a combination of the left row with every row on the right. So the number of rows returned in a CROSS JOIN is the number of rows in the current table, multiplied by the number of rows in the joined table.
In your query, an INNER JOIN or LEFT INNER JOIN will produce a recordset that includes all the fields from the current table structure and will include fields from the joined table as well.
the implicit LEFT component specifies that only records that match the existing table structure should be returned, so in this case only Payment records that match a customer_id in the currently not filtered customer table will be returned.
The number of resulting rows is the number of rows in the joined table that have a match in the current table.
If instead you want to query:
Select all the customers that have payments
then you can use a join, but you should also use a DISTINCT clause, to only return the unique records:
SELECT DISTINCT customer.customer_id
, first_name
, last_name
FROM customer
INNER JOIN payment ON Customer.customer_id = Payment.customer_id
An alternative way to do this is to use a sub-query instead of a join:
SELECT customer_id
, first_name
, last_name
FROM customer
WHERE EXISTS (SELECT customer_id FROM payment WHERE payment.customer_id = customer.customer_id)
The rules on when to use one style of query over the other are pretty convoluted and very dependant on the number of rows in each table, the types of indexes that are available and even the type or version of the RDBMS you are operating within.
To optimise, run both queries, compare the results and timing and use the one that fits your database better. If later performance becomes an issue, try the other one :)
Select the Customer_id field

SQL Query that returns only records with multiple rows

I have a database with two tables: Customers and Services.
The Customer table has account information and the Services table has individual records of every service my company has performed.
The Services table is linked to the Customer table with an ID column where Customers.ID = Services.CustomerID.
I am trying to perform a query which will return the customer name and account number for only those customers where more than one service has been performed within a specified date range. For example, show me all customers where I've performed work more than twice in 2015.
How do I write this type of query so that only those with multiple service visits are returned? I can do this using cursors, counting results, etc. but it seems there must be a more efficient way.
Just use a JOIN and a GROUP BY like so:
SELECT Customers.ID
FROM Customers
JOIN Services ON Customer.ID=Services.CustomerID
--WHERE your Services date check here
GROUP BY Customers.ID -- you can add more columns from the customers table here and in the select as needed
HAVING SUM(1)>1
You can add a WHERE clause to filter the Services' date range (just before the GROUP BY).
Select Id from Customers C where count (select * from Services S where C.id = S.CustomersId ) > 1
SELECT Customers.CustomerID
,Customers.Name
,Customers.AcoountNumber
FROM Customers
JOIN
(
select Services.CustomerID, Services.CustomerID as totalServices
from Services
where Services.date BETWEEN #FROM_DATE AND #TO_DATE
group by Services.CustomerID
having count(Services.CustomerID) >1
) AS CustomersMoreThan1 on Customers.CustomerID=CustomersMoreThan1.CustomerID
This query allows you to add more columns from your Customer table without having to modify your GROUP BY.

Why is my WHERE clause not return the CustomerIDs that are also in the Orders table?

My SQL statements are not returning any results. I am using the table that are on the www.w3schools.com web site. I want to have all of the customer IDS in my Customers table match all of the CustomerIDS in the Orders table. The SQL statement works that it goes through the table and checks every CustomerID to every Orders.CustomersID and when it finds a match doesn't it return that record.
Question: Why does the SQL not return the row when both customerIDS are equal because there are values that will return true?
SQL Statement:
SELECT * FROM Customers WHERE Customers.CustomersID = Orders.CustomersID;
One last thought: What is the best free SQL database that can be downloaded without a lot of hassle for home use?
Try this:
SELECT Customers.*
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
If you just want customers that have orders then use:
SELECT *
FROM Customers
WHERE CustomerID IN
(SELECT CustomerID FROM Orders)
If you use a JOIN you may get multiple records per customer (if the customer has multiple orders). You can solve that with DISTINCT but IMHO a IN clause is cleaner (and likely faster)
You need a query like this: SELECT *
FROM Customers c
INNER JOIN Orders o on c.CustomerID = o.CustomerID;
w3schools is a very bad resource.
Selecting the best database is a bad question for stackoverflow. But the answer is PostgreSQL. (And lots of other DBMSs would fit the bill for you as well.)

Select records for MySQL only once based on a column value

I have a table that stores transaction information. Each transaction is has a unique (auto incremented) id column, a column with the customer's id number, a column called bill_paid which indicates if the transaction has been paid for by the customer with a yes or no, and a few other columns which hold other information not relevant to my question.
I want to select all customer ids from the transaction table for which the bill has not been paid, but if the customer has had multiple transactions where the bill has not been paid I DO NOT want to select them more than once. This way I can generate that customer one bill with all the transactions they owe for instead of a separate bill for each transaction. How would I build a query that did that for me?
Returns exactly one customer_id for each customer with bill_paid equal to 'no':
SELECT
t.customer_id
FROM
transactions t
WHERE
t.bill_paid = 'no'
GROUP BY
t.customer_id
Edit:
GROUP BY summarises your resultset.
Caveat: Every column selected must be either 'grouped by' or aggregated in some fashion. As shown by nikic you could use SUM to get the total amount owed, e.g.:
SELECT
t.customer_id
, SUM(t.amount) AS TOTAL_OWED
FROM
transactions AS t
WHERE
t.bill_paid = 'no'
GROUP BY
t.customer_id
t is simply an alias.
So instead of typing transactions everywhere you can now simply type t. The alias is not necessary here since you query only one table, but I find them invaluable for larger queries. You can optionally type AS to make it more clear that you're using an alias.
You might try the Group By operator, eg group by the customer.
SELECT customer, SUM(toPay) FROM .. GROUP BY customer