I have a Table A with customers and a Table P with products.
I also have a table C which represents the purchased product by customers.
The table fields are as follow:
A (Customers)
user_id
Name
Surname
P (Products)
product_id
price
product name
C (Purchased products)
id
product_id
user_id
quantity
date
C is the many-to-many link between A and P.
Assume that today a customer named "Bob Wright" has bought a product called "Beautiful_magazine". Assume that both customer and product are already in the database.
How do I make the entry in the C table?
I know that I should use the insert into select statement but I am facing hard time because I should retrieve the user id form A and the product id form P and then placing them into a new line in C along with the function NOW() and a numerical values representing the price.
I cannot do that because I am a newbie.
Any hint?
EDIT
I would like to make it manually, using the INSERT statement without relying on the software.
Assume:
user_id: 890
Name: Bob
Surname: Wright
product_id: 4897
price: 5.90
product_name: Beautiful_magazine
I need to create a new line in C table as follow:
id (autoincremental)
product_id: 4897
user_id: 890
quantity: 1
date: '2017-2-20'
Obviously, the product_id and user_id from P and A should be retrieve through a select statement using the where statement.
If you are passing the data in from an application, use a procedure (assuming that the id auto increments)
CREATE PROCEDURE `AddSale` (IN ProdID INT, IN UserID INT, IN Qty INT)
BEGIN
insert into TableC (Product_ID, User_ID, Quantity, Date)
values (ProdID, UserID, Qty, Now());
END
In your application, call the procedure and passin the parameters
Related
I have a table that contains all the transaction information
(transaction date, customer name, transaction amount, unit amount, store ID).
How to create a table which could properly show the stores that customer has visited? The customer could make purchase from multiple stores, so the relationship between customer and store should be one to many. I am trying to check the stores each customer had visited.
Example:
Transaction table
store_ID
transaction_date
customer_name
transaction_amount
transaction_unit
Expected Output
customer_name
store_list
This is just a Hypothesis problem. Maybe list all shopped store seprately could be better? (But I guess it might create chaos if we want to check customer who made purchase in those stores). Thanks in advance :)
Since you already have a table with all information needed, maybe you are asking for a view, to avoid denormalized/duplicated data.
Example is shown below. Here I will use sqlite syntax (text instead of varchar, etc). We are normalizing data to avoid problems - for example you have shown a table with customer names, but different customers can have the same name, so we use customer_id instead.
First the tables:
create table if not exists store (id integer primary key, name text, address text);
create table if not exists customer (id integer, name text, document integer);
create table if not exists unit (symbol text primary key);
insert into unit values ('USD'),('EUR'),('GBP'); -- static data
create table if not exists transact (id integer primary key, store_id integer references store(id), customer_id integer references customer(id), transaction_date date, amount integer, unit text references unit(symbol));
-- transaction is a reserved word, so transact was used instead
Now the view:
-- store names concatenated with ',' using sqlite's group_concat
create view if not exists stores_visited as select cust.name, group_concat(distinct store.name order by store.id) from transact trx join customer cust on trx.customer_id=cust.id join store on trx.store_id=store.id group by cust.name order by cust.id;
-- second version, regular select with multiple lines
-- create view if not exists stores_visited as select cust.id, cust.name, store.id, store.name from transact trx join customer cust on trx.customer_id=cust.id join store on trx.store_id=store.id;
Sample data:
insert into store values
(1,'store one','address one'),
(2,'store two','address two')
(3,'store three','address three');
insert into customer values
(1,'customer one','custdoc one'),
(2,'customer two','custdoc two'),
(3,'customer three','custdoc three');
insert into transact values
(1,1,1,date('2021-01-01'),1,'USD'),
(2,1,1,date('2021-01-02'),1,'USD'),
(3,1,2,date('2021-01-03'),1,'USD'),
(5,1,3,date('2021-01-04'),1,'USD'),
(6,2,1,date('2021-01-05'),1,'USD'),
(7,2,3,date('2021-01-06'),1,'USD'),
(8,3,2,date('2021-01-07'),1,'USD');
Testing:
select * from stores_visited;
-- customer one|store one,store one,store two
-- customer three|store one,store two
-- customer two|store one
I am hoping someone can help me with this SQL view.
I have a screen where you can add products to an order. This order is for a customer which may or may not have a special price for the item.
Essentially, I am after 3 figures:
The unit price for the product as input by the operator
The default price for the product (standard ratecard)
The special price for the client for this product (may not exist)
To simplify things, I have the following tables
OrderLine
OrderId
ProductId
ProductVariationId (can be null)
Ratecard
RatecardId
RatecardName
RatecardClient (Default master ratecard is ID 1)
RatecardClientId
RatecardId
ClientId
RatecardProduct
RatecardProductId
ProductId
ProductVariationId (can be null)
A product has an ID but can also have a product variation ID
I want to create a view for OrderLine which has the input price, the default ratecard price and the special price for that product.
I would like a view which gives me:
Product Id
UnitPrice From "OrderLine"
RatecardPrice From "RatecardProduct" relating to "Ratecard" with RatecardId = 1 (will always exist)
ClientRatecardPrice (Depends if there is an existing ratecard and entry in this ratecard for the client / product / variation )
I'm really hoping someone can get me started here as I'm really struggling!
Thank you in advance!
I have made some assumptions about where the price columns are, and also how the RateCardProduct joins to RateCard. It would be better if you included the actual table definitions with extra columns stripped out. But with the assumptions you can see in my table defs, this query should give you what you want.
create table ClientOrder(OrderID int, ClientID int)
create table OrderLine(OrderId int,ProductId int,ProductVariationId int, UnitPrice decimal(10,2))
create table Ratecard(RateCardId int,RatecardName varchar(50)) -- has default 1
create table RateCardClient(RatecardClientId int,RatecardId int,ClientId int)
create table RateCardProduct(RatecardProductId int, RateCardId int, ProductId int, ProductVariationId int, Price decimal(10,2))
select Clientorder.ClientID, ClientOrder.OrderID, OrderLine.ProductID, OrderLine.ProductVariationId,
OrderLine.UnitPrice as UnitPrice,
P1.Price as RateCardPrice,
P2.Price as ClientRateCardPrice
from ClientOrder
Join OrderLine on OrderLine.OrderID=ClientOrder.OrderID
-- Get the default price
join RateCardProduct P1 on P1.RateCardID=1
and P1.ProductId=OrderLine.ProductId
and isnull(P1.ProductVariationID,0)=isnull(OrderLine.ProductVariationID,0)
-- Get the customer specific price
left join RateCardClient on RateCardClient.ClientID=ClientOrder.ClientID
left join RateCardProduct P2 on P2.RateCardID=RateCardClient.RateCardID
and P2.ProductId=OrderLine.ProductId
and isnull(P2.ProductVariationID,0)=isnull(OrderLine.ProductVariationID,0)
For example, I have two tables, one of them I have the product description, in another I have data like "price", "date of registration", among others. I would like to know how I can delete the description that does not have id in the product table.
Something like:
delete from ProductDescription
where productId not in (
select productId from Product
);
Consider if we have two tables
Product table
Id-----Description
---------------------------------
1------It is abcd
2------It is Efg
3------It is Xyz
Product table
Id------Name------price---date
-----------------------
1-------Abcd------10-----1/1/2007
2-------Efg------20-----2/2/2007
We need to delete decription 'Its xyz' which doesnot have id in product table.
So use this query
delete from Description
where Id not in (
select Id from Product
);
I have DB2 table "organization" which holds organizations data including the following columns
organization_id (PK), name, description
Some organizations are deleted so lot of "organization_id" (i.e. rows) doesn't exist anymore so it is not continuous like 1,2,3,4,5... but more like 1, 2, 5, 7, 11,12,21....
Then there is another table "title" with some other data, and there is organization_id from organization table in it as FK.
Now there is some data which I have to insert for all organizations, some title it is going to be shown for all of them in web app.
In total there is approximately 3000 records to be added.
If I would do it one by one it would look like this:
INSERT INTO title
(
name,
organization_id,
datetime_added,
added_by,
special_fl,
title_type_id
)
VALUES
(
'This is new title',
XXXX,
CURRENT TIMESTAMP,
1,
1,
1
);
where XXXX represent "organization_id" which I should get from table "organization" so that insert do it only for existing organization_id.
So only "organization_id" is changing matching to "organization_id" from table "organization".
What would be best way to do it?
I checked several similar qustions but none of them seems to be equal to this?
SQL Server 2008 Insert with WHILE LOOP
While loop answer interates over continuous IDs, other answer also assumes that ID is autoincremented.
Same here:
How to use a SQL for loop to insert rows into database?
Not sure about this one (as question itself is not quite clear)
Inserting a multiple records in a table with while loop
Any advice on this? How should I do it?
If you seriously want a row for every organization record in Title with the exact same data something like this should work:
INSERT INTO title
(
name,
organization_id,
datetime_added,
added_by,
special_fl,
title_type_id
)
SELECT
'This is new title' as name,
o.organization_id,
CURRENT TIMESTAMP as datetime_added,
1 as added_by,
1 as special_fl,
1 as title_type_id
FROM
organizations o
;
you shouldn't need the column aliases in the select but I am including for readability and good measure.
https://www.ibm.com/support/knowledgecenter/ssw_i5_54/sqlp/rbafymultrow.htm
and for good measure in case you process errors out or whatever... you can also do something like this to only insert a record in title if that organization_id and title does not exist.
INSERT INTO title
(
name,
organization_id,
datetime_added,
added_by,
special_fl,
title_type_id
)
SELECT
'This is new title' as name,
o.organization_id,
CURRENT TIMESTAMP as datetime_added,
1 as added_by,
1 as special_fl,
1 as title_type_id
FROM
organizations o
LEFT JOIN Title t
ON o.organization_id = t.organization_id
AND t.name = 'This is new title'
WHERE
t.organization_id IS NULL
;
I have two table which have one to many relationship
Example :
Table Buy : BuyID, BuyName
Table BuyItems: BuyItemID, Buy_BuyID, Quantity, Amount
Now I want to create trigger so whenever user insert to table buy, I can insert to table :
Buy_Summary :
TotalQuantity (which is sum from all quantity in table BuyItems which from record Buy.BuyID=BuyItems.Buy_BuyID)
TotalAmount (which is sum from all amount in table BuyItems which from record Buy.BuyID=BuyItems.Buy_BuyID)
How can I do this?