select column from child table in select clause - sql

Is there any way in SQL server to get the child records to be displayed as the fields of the select clause of master table?
Suppose a master table Sales and a child table called Purchaseditems.
The SaleId is referenced in the Purchaseitems table.
So for a sale, there are lot of purchase items.
If so, how I can write a query to select each sales with its purchased items in the select clause?
This is a kind of dynamic column selection from child table. Is this possible in SQL server?

Not sure if i'm getting the wrong idea here, but isn't this just a simple join:
select s.saleid, p.*
from sales s, purchaseditems p
where s.salesid = p.salesid;

Related

sql can't check column1>column2 not working

I have some problem in sql syntax.
i have products table and below two column
total_quantity (Its total quantity for products)
remain_alert_quantity
i want to get records that are below remain_alert_quantity
select * from products where total_quantity<remain_alert_quantity
but its not work .
can i check condition with column value in sql.
thanks and regards.
Given data is not sufficient so I am assuming few thing like,
you want to compare the product quantity with the remain_alert_quantity of same product.
There is some unique column in table (like product_id)
in this case try the below query.
select * from products a where a.total_quantity<
(select b.remain_alert_quantity from products b where b.product_id=a.product_id);

Left Join on three tables in access with Group by

I have broken my head with syntax error response from Access Jet engine.
I have three tables.
First one "tblMstItem" is the master table for Item details contains two columns "colITemID" PK and "colItemName"
Second one "tblStocks" is the table where the purchases are maintained. This table has a column "colRQty" which keeps the quantity of the particular item purchased. "colItemID" FK from "tblMstItem"
Third one "tblSales" is the table where the sales are maintained. This table has a column "colSoldQty" which keeps the quantity of the particular item sold. "colItemID" FK from "tblMstItem"
Therefore "colItemID" is common in all the three tables and has links created.
My requirement is I need all the Items listed in the "tblMstItem" table columns are "colItemID" "colItemName" and if there is any item purchased or any item sold should be shown as sum of that particular item.
I have used Left Join shown in the following select statement but it always giving me an error message.
Select statement as follows:
SELECT
i.colItemID,
i.colItemName,
s.rqty,
n.soldqty
from tblMstItem i
left join
( select sum( colRQty ) as rqty from tblStocks group by colItemID ) s
on i.colItemID = s.colItemID
left join
( select sum( colSoldQty ) as soldqty from tblSales group by colItemID ) n
on i.colItemID=n.colItemID``
I tried the above given code with many different syntax but every time I get syntax error. It is making me to doubt do MS Access support three table joins, I am sure I am wrong.
See the error Message below
Table columns and table link shown below
I would be very thankful to get any help on this. Access sql please because this I am able to get results in SQL Server.
Thanks in Advance
MS Access has a picky syntax. For instance, joins need extra parentheses. So, try this:
select i.colItemID, i.colItemName,
s.rqty, n.soldqty
from (tblMstItem as i left join
(select colItemID, sum(colRQty ) as rqty
from tblStocks
group by colItemID
) as s
on i.colItemID = s.colItemID
) left join
(select colItemID, sum( colSoldQty ) as soldqty
from tblSales
group by colItemID
) as n
on i.colItemID = n.colItemID;
You also need to select colItemID in the subqueries.

store select result in variable and use in where condition

A have 3 SQL queries that I put together using union.
The first 2 queries return unique Order ID's but the third query repeats Order ID's from the first 2.I need to exclude those results in query 3 .
Example:
QUERY 1:
SELECT DISTINCT
ORDER_ID,
PRODUCT
FROM
ORDERS
WHEN TYPE=A
query 1 sample data {12121212,13131313}
QUERY 2:
SELECT DISTINCT
ORDER_ID,
PRODUCT,
FROM
ORDERS
WHEN CATEGORY=X
Query 2 sample data {14141414,15151515}
QUERY 3:
SELECT DISTINCT
ORDER_ID,
PRODUCT
FROM
ORDERS
WHEN TYPE=C
Query 3 sample data {17171717,12121212,14141414}
So query 3 repeats data from query 1 and 2. The real data is much larger. What I am trying to is to use the results of the first 2 queries to be excluded from query3
query1
union
query2
union
SELECT DISTINCT
ORDER_ID,
PRODUCT
FROM
ORDERS
WHEN TYPE=C
AND
ORDER_ID NOT IN (Variable1=ORDER_ID IN QUERY1,Variable2=ORDER_ID IN QUERY2)
Desired data {12121212,13131313,14141414,15151515,16161616,17171717}
How can I store variables to use in the where condition ?
Appreciate any help
It seems (but it is really hard to guess with any certainty) that you maybe want to do hierarchical data gathering, whether data is selected from 1st available source (from prioritized list), that has it, and next sources would get ignored.
Best of all I think would be making a persistent table having it all:
ORDER_ID, PRODUCT, Source_Priority
Such a table would track up-to-date data from all the tables (for example by AFTER UPADTE OR INSERT OR DELETE trigger on ORDERS and other sources) and then your query would be reformulated as "query new table, get rows with maximum-per-ORDER_ID-value-of-Source_Priority", which was asked many times, and is solved by one JOIN in Firebird 2 or by Window Functions in Firebird 3.
If you do not want to have a dedicated persistent prioritized table, You can do it, using
Global Temporary Table to do the sorting
https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-gtt
MERGE command to do conditional inserts (clearing the table before it)
https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-dml-merge.html
SELECT to read the data from prepared GTT
If you want to pretend that would be one query, not 2+N, then you can hide them inside
a named Stored Procedure or an anonymous EXECUTE BLOCK https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-dml-execblock.html
Something like that:
Create GLOBAL TEMPORARY TABLE TMP_ORDERS
( ORDER_ID integer PRIMARY KEY,
PRODUCT VarChar(10) );
And then replace your "one true query" with this sequence (maybe hidden inside the Execution Block if need be)
DELETE FROM TMP_ORDERS;
INSERT INTO TMP_ORDERS
SELECT DISTINCT
ORDER_ID,
PRODUCT
FROM
ORDERS
WHEN TYPE=A;
MERGE INTO TMP_ORDERS as Dest
USING (
SELECT DISTINCT
ORDER_ID,
PRODUCT,
FROM
ORDERS
WHEN CATEGORY=X
) as Src
WHEN NOT MATCHED THEN
INSERT(Dest.ORDER_ID, Dest.PRODUCT) VALUES(Src.ORDER_ID, Src.PRODUCT);
MERGE INTO TMP_ORDERS as Dest
USING (
SELECT DISTINCT
ORDER_ID,
PRODUCT,
FROM
ORDERS
WHEN TYPE=C) as Src
WHEN NOT MATCHED THEN
INSERT(Dest.ORDER_ID, Dest.PRODUCT) VALUES(Src.ORDER_ID, Src.PRODUCT);
SELECT * FROM TMP_ORDERS;
P.S. but why did your partial queries even contained DISTINCT ? Isn't ORDER_ID already your primary key there, which can never be non-distinct, to start with?
you can try this
select * from
(SELECT DISTINCT
ORDER_ID,
PRODUCT
FROM
ORDERS
where TYPE='A') as q1,
(SELECT DISTINCT
ORDER_ID,
PRODUCT
FROM
ORDERS
WHERE CATEGORY='X'
) as q2,
(SELECT DISTINCT
ORDER_ID,
PRODUCT
FROM
ORDERS
where TYPE='C') as q3
WHERE q1.order_id=q2.order_id

duplicated rows in select query

I am trying to run a query to get all the customers from my database. These are my tables in a diagram :
when running the query by joining the table Companies_Customers and the Customers table based on the customerId in both tables(doesn't show in the join table in the pic), I get duplicate rows, which is not the desired outcome.
This is normal from a database standpoint since a Customer can be related to different companies (Companies can share single customer).
My question is how do I get rid of the duplication via SQL.
There can be 2 approaches to your problem.
Either only select data from Customers table:
SELECT * FROM Customers
Or select from both tables joined together, but without CompanyName and with GROUP BY CompanyCustomerId - although I highly suggest the first approach.

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

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.