简体   繁体   中英

Temporary table and SQL request

I have to make a temporary table for a query but I do not see how to formulate it.

I have to create a temporary table containing for each customer and product, the total quantity ordered from the product by the customer in all orders.

Here are the tables and the fields :

Customer (Nocust (PK), CTotMont, Nborder)
Product (Noprod (PK), Pxunit, Qtestk)
Order (Noorder (PK), Montorder, Nocust)
Line (Noorder (PK), Nordre (PK), Qteorder, Puacc, Noprod, Monttline)

• Nocust is the customer number.

• CtotMont indicates the amount spent by the customer (type: smallmoney).

• Nborder indicates the total number of orders made by a customer.

• Noprod is the product number.

• Pxunit indicates the unit price of a product (type: smallmoney).

• Qtestk indicates the number of available items of a certain product. This value must always be> 0.

• Montorder indicates the amount of an order (type: smallmoney).

• A number order Noorder consists of several lines numbered by Nordre

• Qteorder indicates the number of items ordered.

• Puacc indicates the unit price granted (not necessarily the unit price, type smallmoney).

• Montline is an attribute calculated by Puacc * Qteorder (as Puacc * Qteorder)

I try to start :

select Qteorder, Nocust, Noprod 
into #Qtetotale
from line 
join order on line.noorder=order.noorder 
group by Noprod, Nocust, Qteorder

proceed as follow:

create table #Temp
(
    Qteorder int, 
    Nocust Varchar(50), 
    Noprod Varchar(50), 
)

;WITH all_items
AS (
select Qteorder, Nocust, Noprod 
from line 
join order on line.noorder=order.noorder 
group by Noprod, Nocli, Qtecom
) 

Insert Into #Temp
Select Qteorder,Nocust ,Noprod  from all_items

When done, don't forget to drop the temp table

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

In SQL Server there are two types of temporary tables which are stored in tempdb system database.

  1. Local temp table : accessible within the connection

    Syntax: CREATE TABLE #tablename(column datatype,column1 datatype,...)

  2. Global temp table : can be accessed across all connections while the base connection is active

    Syntax: CREATE TABLE ##tablename(column datatype,column1 datatype,...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM