SQL Server : make use of foreign key [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have 2 tables Product and Vendors. In my Product table, I have a primary key and one foreign key VendorID which references the primary key of the Vendors table:
So, what I was trying to do is to determine which products have a quantity of less than 1000 then display the product's vendor ID and name.
I tried doing this:
SELECT VendorID, Name
FROM Vendors, Product
WHERE Quantity < 1000;
but I get an error
Ambiguous column name 'VendorID'
This is the only solution I can think of since I am just only a beginner in using SQL
I think the output must go like this
VendorID Name
--------------------------------------------
V00002 Liwayway Marketing Corporation 8
V00003 Monde Nissin

Try this:
USE myDB;
SELECT v.VendorID, v.Name
FROM Vendors v JOIN Product p
ON v.VendorID = p.VendorID
WHERE p.Quantity < 1000;

It is happening because your program doesn't know which Vendors or Product table to choose from.
I would try to make a union, like NATURAL JOIN which will make your tables "combine", else, you will get every row of Vendors paired with every row of Product.
Plus: the tables are different, so you have to "pair" them so you can use attributes from the two of them.

Related

Sql performance query multiple conditions on same column [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a table ORDERS with ORDER_ID and SERVICE_ID field.
I can have multiple entries in table like:
ID ORDER_ID SERVICE_ID
1 000001 1
2 000001 2
3 000001 3
4 000002 1
5 000002 2
I need to final all orders that have entries for service_id 2 but not for service_id 3.
My query is:
SELECT * FROM ORDERS
WHERE SERVICE_ID = 2
AND ORDER_ID NOT IN (SELECT ORDER_ID FROM ORDERS WHERE SERVICE_ID = 3)
Is there another way to do this in order to improve performance?
Thanx
Use NOT EXISTS which generally performs better than NOT IN:
SELECT * FROM ORDERS O
WHERE O.SERVICE_ID = 2
AND NOT EXISTS
(SELECT 1 FROM ORDERS OO WHERE OO.ORDER_ID = O.ORDER_ID AND OO.SERVICE_ID = 3)
Another way to achieve this would be
select * from orders o1
where service_id = 2
and not exists (
select * from orders o2
where o1.order_id = o2.order_id
and o2. service_id = 3)
But no one will be able to tell you whether any of these will give performance problems due to the following:
As long as your data volume is small, performance will be good no matter how your query is written.
When your query needs optimization, the DBMS optimizer will try to do its best. You can find out what it did and whether it suggests improvements using its "explain" feature (that's what it's called in MS SQL Server, might have a different name for your DBMS) on the actual query on the actual data.
One way to optimize performance is to introduce an index for each attribute (combination) used as selection criteria. In your case that would be order_id and service-id.
Defining a few indexes isn't much work, so you might do it right beforehand. As for other precautions, I would wait until performance issues really turn up, which will probably never happen.

SQL Server Temp Table to a Select Distinct Count Distinct quetsion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Ok, basically I've got a lot of temp tables I've created and I'm trying to create Validation for the ProvDiff table.
DROP TABLE #ProvDiff;
IF OBJECT_ID ('temp.dbo.#ProvDiff') IS NOT NULL
DROP TABLE #ProvDiff;
SELECT *
INTO #ProvDiff
FROM
(SELECT DISTINCT *
FROM #finalclaimswithflags f
WHERE f.[Pay-To Prov NPI] <> f.[Rendering Prov NPI]) ProvDiff;
SELECT DISTINCT COUNT(DISTINCT ???) AS 'Unique EI NPIS'
FROM #ProvDiff
In my head it seems like the differences should be able to produce a result and I should be able to do a count on that. But for the life of me I can't figure out how to do that. If I do a count on rendering or pay to then those numbers wouldn't necessarily reflect the value for what are above. I know how many of each are produced for above validation.
Any help would be greatly appreciated
Is this what you want?
SELECT COUNT(*)
FROM (SELECT DISTINCT *
FROM #finalclaimswithflags f
WHERE f.[Pay-To Prov NPI] <> f.[Rendering Prov NPI]
) ProvDiff;
I don't see why a temporary table would be used for this.
For better or worse, SQL Server does not support select count(distinct *), so you pretty much need a subquery.

SQL: Need to select items by different conditions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My table looks like this -
Explanation
I'm working on an online shop that sells tours and spa. I'm showing all together on one page.
What I need to select?
1. All spa products (based on "Spa" column), no conditions.
2. All parent tours that have children with an upcoming date.
Meaning
Products ID 1, 4, 5.
Why?
Product 6 have a child, but from 1999. And although product 1 have one child at 2000, it has another one in 2017. All spa products are selected by default, without conditions.
I hope I made my question clear as I could. I would appreciate any help, my SQL is really bad.
Your data structure isn't great. Really, as you have a parent -> child relationship as well as special types, it would be better to have three tables e.g. Product, ProductType and ProductItem or some such nomenclature. The parent table contains the ID, name and typeId (having a flag limits you to only two types, you may chooes to have more). Your child table contains a ID, parent ID, name and date. Then you can simply use a foreign key constraint to link the two and do some simple SQL to join it all up e.g.
SELECT pt.Name, pi.Name, pi.Date from ProductItem pi
INNER JOIN Product p on p.id = pi.parentID
INNER JOIN ProductType pt on p.typeId = pt.id
WHERE pi.date > now() --The "Now" part depends on your RDBMS as it's different on different systems
AND pt.name = "TOUR"
UNION
SELECT pt.Name, p.Name, 'N/A' from Product p
INNER JOIN ProductType pt on pt.id = p.typeId
WHERE pt.name = "SPA"

SQL - What syntax to use? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a table named "product_to_category" with 2 column "product_id and category_id".
I have about 500 product ID with 1000 category ID associate with it.
Now I want to add another category ID into all the product ID.
What syntax should I use to make this happen?
Thank you.
Are you looking for this?
INSERT INTO product_to_category(product_id, category_id)
SELECT product_id, 25 -- < new category that you want to add
FROM product_to_category
GROUP BY product_id
That will add category with id 25 to all unique products that you already have in product_to_category. If not all of your products have at least one category defined, then you can select from some product table that I'm sure you have.
Here is SQLFiddle demo
Use something like this:
UPDATE product_to_category
SET category_id=('your_new_category_id')
WHERE product_id = your_product_id;
Remember the Where clause, otherwise this will update all your rows.
The Where clause could also contain a SELECT statement that would select all product_id's for all your products that need to update their category.
Something like:
UPDATE product_to_category
SET category_id=('your_new_category_id')
WHERE product_id = (SELECT product_id .... condition);

multiple calculations across tables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to get the total cost of all the invoices for a customer. Ideally the end format will be two columns [customer name] and [total of invoices]. I have broken it down into the parts so far so I can check and better understand the process of joining the tables and have done a calculation to get the total of items on each invoice but now I am stuck.
As you can see from my screenshot ( Had to link to my google docs as I couldn't post the image up here - sorry) I am getting the company name listed multiple times. Once for each item and also for each invoice number and then item. How can I change my query to show the customer name only once with the corresponding totals of all the invoices combined?
I have lines 3 and 4 as comments of what I think is next so I can work this in steps before fine tuning the query to my desired output.
Thanks
Select Customer.CustName, Sum(InvoiceItem.Quantity*Item.ItemPrice) As TotalValue
From Customer
Inner Join Invoice On Customer.CustABN = Invoice.CustABN
Inner Join InvoiceItem On Invoice.InvoiceNo = InvoiceItem.InvoiceNo
Inner Join Item On InvoiceItem.ItemNo = Item.ItemNo
Group By Customer.CustName
Something like this should work using SUM and GROUP BY:
SELECT CustomerName, SUM(itemPrice * qty) InvoiceTotal
FROM YourTables With Your Joins
GROUP BY CustomerName
If you posted your entire query above, I could copy and paste into the example. But this should get you going in the right direction.
grouping could help, also you need to check if your dbms allows grouping without using agregate functions (some DBMS do not allw it, and return misleading results).
multiple companies is because of the relation company-invoice-product i guess.