Fetch single data from table in sql? - sql

I have three tables in my SQL Server
1.) Registration it's columns
Reg_Id bigint, primary key and auto increment
Name nvarchar(50),
Tranx_id nvarchar(30),
Email nvarchar(30),
Username nvarchar(30),
Password nvarchar(30),
Edition_Id nvarchar(50),
Default_Id nvarchar(50),
Reg_Date datetime,
usertype nvarchar(50),
2.) AllEditionPages it's columns
Page_id bigint, primary key and auto increment
edition_date datetime,
noofpages int,
Page_no int,
image_path nvarchar(50),
Active int,
type_of_page varchar(50),
Image_Width int,
Image_Height int,
3.) Edition
id int, primary key and auto increment
edition_date datetime,
noofpages int,
XMLFile nvarchar(50),
PDFFile nvarchar(50),
PDFPrefix nvarchar(50),
type nvarchar(50),
price nvarchar(50),
reg_req nvarchar(50)
As per above table I try below sql query
SELECT edi.*, aep.*, reg.*
FROM Edition as edi INNER JOIN Registration as reg
ON edi.id = reg.Edition_Id INNER JOIN AllEditionPages as aep
ON edi.edition_date = aep.edition_date
where reg.Edition_Id= edi.id
and reg.Reg_ID = 14
From this query I get this output:
id edition_date type price page-id
96 2012-07-18 00:00:00.000 free null 2503
96 2012-07-18 00:00:00.000 free null 2503
I get in output two rows, but want only single row in output

You can use common table expression in this scenario in following way:
WITH cteTable AS
(
SELECT edi.*, aep.*, reg.*
FROM Edition as edi INNER JOIN Registration as reg
ON edi.id = reg.Edition_Id INNER JOIN AllEditionPages as aep
ON edi.edition_date = aep.edition_date
where reg.Edition_Id= edi.id
and reg.Reg_ID = 14
)
select top 1 * from cteTable
As you two table contains edition_date, you need to spcify the column name instead of using "*" in following way:
WITH cteTable AS
(
SELECT edi.id,edi.edition_date,edi.noofpagez,edi.XMLFile,edi.PDFFile ,edi.PDFPrefix,edi.type,edi.price,edi.reg_req ,
aep.Page_id, aep.edition_date,aep.noofpages,aep.Page_no,aep.image_path,aep.Active,aep.type_of_page,aep.Image_Width,aep.Image_Height,
reg.Reg_Id,reg.Name,reg.Tranx_id,reg.Email,reg.Username,reg.Password,reg.Edition_Id,reg.Default_Id,reg.Reg_Date,reg.usertype
FROM Edition as edi INNER JOIN Registration as reg
ON edi.id = reg.Edition_Id INNER JOIN AllEditionPages as aep
ON edi.edition_date = aep.edition_date
where reg.Edition_Id= edi.id
and reg.Reg_ID = 14
)
select top 1 * from cteTable

You have to specify one row.From your putput it looks like you have duplicate data and if that is the issue you should use distinct to get distinct rows..Otherwise specify what exactly you need.

You can use select distinct if the 2 rows have the same value, or you can simple use LIMIT 0,1 behind your query.

Related

Trying to aggregate quantities across multiple tables SQL

I'm building a stock synch which compares product quantities from three different tables:
EWM
USOR
DSOR
The maths behind the stock synch is EWM - (USOR + DSOR) = Misalignment
The EWM table divides the product quantities by the different storage types that products are held in which necessitates the need to have the quantities aggregated before being used in the end query but I keep getting the wrong figure after aggregating the quantities so I think I'm doing something wrong but I can't seem to spot it.
Here's my code:
--Table for EWM Data--
create table EWM(
Date_loaded date,
Sap_code bigint,
Product_description varchar(100),
Location nvarchar(50),
Storage_type varchar(50),
Quantity int,
Sap_batch nvarchar(50),
Expiry_date date,
Stock_type varchar(50)
);
--Table for USOR Data--
create table USOR(
Date_Loaded date,
Sap_Code bigint,
Product_description varchar(100),
Pack nvarchar(50),
Cost_price decimal,
Trade_price decimal,
Stock int,
Location nvarchar(50),
);
--Table for DSOR--
create table DSOR(
Date_Loaded datetime,
Sap_code bigint,
Product_description varchar(100),
Bin_location nvarchar(50),
Location varchar(50),
Pack nvarchar(50),
Units int,
Total int,
);
--Table for difference between EWM and USOR+DSOR--
create table Misalignment
(
Date_loaded date,
Sap_code bigint,
Product_description varchar(100),
Pack nvarchar(50),
Location nvarchar(50),
Total_difference int
)
--Inserting data in Misalingment using query from USOR, USOR_DSOR, EWM --
WITH x AS (
SELECT SAP_Code, Quantity
FROM EWM
GROUP BY SAP_Code, Quantity
)
insert into Misalignment(Date_Loaded, Sap_code, Product_description, Location, Total_difference)
Select USOR.Date_Loaded, USOR.Sap_Code, USOR.Product_description, USOR.Location, sum(x.Quantity - (USOR.stock + DSOR.Total))as Total_difference
FROM x
INNER JOIN USOR ON x.SAP_Code = USOR.SAP_Code
INNER JOIN DSOR ON x.SAP_Code = DSOR.SAP_Code
group by USOR.Date_Loaded, USOR.Sap_Code, USOR.Product_description, USOR.Pack, USOR.Location
select * from Misalignment
where Total_difference > 0
order by Total_difference
desc
I ran the query below to test my code out:
select * from ewm
where Date_loaded = '2020-10-05' and Sap_code = 1002945
select * from DSOR
where Sap_code = 1002945 and Date_loaded= '2020-10-05'
select * from Misalignment
where Sap_code = 1002945 and Date_loaded = '2020-10-05'
This was the result:
The actual result should be 0.
Any suggestions?

Preparing Rules Based List for Promotions

I am trying to put together a promotions list based on a set of rules
In table #productdetail I need to pick up items that have available =1 or available =2 and expected <=08052019 and not_sellable =0
From #product table I need to join id with pid in #productdetail and coalesce (vendor_id to get the vendor_id
Using the vendor_id that I have got from the step above i need to get the vendorname from #vendor table..
From the #Asin table I need to select the latest lastconfirmedasin from the list of items selected in step 1 and also ensure that I should not pick up data from rows where disable =1
From the #pageviews table I need to get the number of pageviews perday for every item based on the lastconfirmedasin for the list of items selected in step 1
Here for every item if I have datetype =day and also datetype =month then I need to select data from datetype =day and select sum(pageviews)/count of days to get the sum of pageviews per day
Also if I have only datetype =month then I need to select (sum(pageviews)(count of rows that have month)/30
Then in the promo table I need to select the average promo% got for the items selected in step 1..The average promo% is calculated as avg((pre_promo_price-promo_price)/promo_price*100))...This will be calculated at the vendor level...So if the vendor has 3 items then the average promo% is calculated as avg([avg((pre_promo_price-promo_price)/promo_price*100)
Then the cost is taken based on if in the table #promo has the date in between or included in promo_start and promo_end (for example today's date being 08/16/2019 is included then the pre promo cost is to taken as the cost for that item otherwise the cost from #product_detail table should be taken
Then I am calculating the priority of the items by vendor(meaning within each vendor ) prioritizing the items based on the power(calculated as pageviewsperday*price)-Higher value of an item within a vendor gets the first priority
The tables:
create table #productdetail
(
itemid int,
available int,
expected date,
isnotsellable int,
pid int,
vendor_id varchar(50),
cost float,
price float)
insert into #productdetail values
('123','1',NULL,'1','1','201','180','200'),
('125','2','08/05/2019','0','1','NULL','40','60'),
('127','1',NULL,'0','1','201','60','80'),
('129','2',NULL,'0','2','203','80','100'),
('131','1',NULL,'0','2','203','70','90'),
('133','1',NULL,'1','2','203','90','110'),
('135','1',NULL,'0','7','206','110','130'),
('137','1',NULL,'0','8','207','120','140'),
('139','1',NULL,'0','8','207','30','50'),
('141','1',NULL,'0','8','207','40','60'),
('143','1',NULL,'0','11','210','60','80'),
('145','1',NULL,'0','11','210','70','90'),
('147','1',NULL,'1','11','210','50','70'),
('149','1',NULL,'0','11','210','20','40'),
('151','1',NULL,'0','15','211','30','50'),
('153','1',NULL,'0','16','NULL','40','60'),
('155','2','08/29/2019','1','15','211','60','80'),
('157','2','08/04/2019','1','18','216','30','50'),
('159','2','08/06/2019','0','19','217','20','40'),
('161','2','08/03/2019','0','20','218','60','80'),
('163','2','08/15/2019','0','21','NULL','90','110')
create table #product
(id int,
vendor_id varchar(50)
)
insert into #product values
('1','201'),
('1','201'),
('1','201'),
('2','203'),
('2','203'),
('2','203'),
('7','NULL'),
('8','207'),
('8','207'),
('8','207'),
('11','210'),
('11','210'),
('11','210'),
('11','210'),
('15','211'),
('15','211'),
('15','211'),
('16','206'),
('18','216'),
('19','NULL'),
('20','218'),
('21','219')
create table #vendor
(vendor_id varchar(50),
vendorname varchar(50)
)
insert into #vendor values
('201','cola'),
('203','foam'),
('207','fill'),
('210','falon'),
('211','chiran'),
('216','Hummer'),
('218','sulps'),
('219','culp'),
('217','jko'),
('206','JINCO')
create table #asin
(disable int,
item_id int,
lastconfirmed datetime2,
lastconfirmedasin varchar(50)
)
insert into #asin values
('0','123','12/19/18 10:19 PM','iopyu'),
('1','123','12/19/16 10:19 PM','hjyug'),
('1','125','5/19/19 10:19 PM','uirty'),
('0','125','12/19/16 10:19 PM','1yuio'),
('0','127','2/19/19 10:19 PM','klbnm'),
('1','127','12/19/18 10:19 PM','lopgh'),
('0','127','12/19/16 10:19 PM','nmbh'),
('0','129','11/19/16 10:19 PM','jklh'),
('0','131','11/19/19 10:19 PM','werat'),
('1','133','6/19/19 10:19 PM','vbnwe'),
('0','133','1/19/19 10:19 PM','mnwer'),
('0','133','11/19/17 10:19 PM','sdert'),
('0','135','6/19/19 10:19 PM','vbsdx'),
('0','137','6/19/17 10:19 PM','bnxct')
create table #pageviews
(startdate date,
lastconfirmedasin varchar(50),
noofpageviews int,
datetype varchar(20))
insert into #pageviews values
('05/08/2017','hjyug','102','day'),
('09/05/2017','hjyug','201','day'),
('10/05/2019','hjyug','1002','day'),
('09/05/2018','iopyu','345','month'),
('10/06/2018','iopyu','545','month'),
('06/05/2019','1yuio','300','day'),
('06/06/2019','1yuio','200','day'),
('09/04/2019','uirty','150','day'),
('11/4/2019','uirty','200','day'),
('12/4/2019','nmbh','300','day'),
('04/15/2019','lopgh','400','day'),
('04/15/2019','klbnm','500','day'),
('04/16/2019','klbnm','1000','day'),
('04/15/2019','jklh','600','day'),
('04/15/2019','werat','700','day'),
('04/15/2019','sdert','800','day'),
('04/15/2019','mnwer','900','day'),
('04/15/2019','vbnwe','1000','day'),
('04/15/2019','vbsdx','1100','day'),
('04/25/2019','vbsdx','3000','day'),
('04/15/2019','bnxct','1200','month'),
('05/31/2019','bnxct','2200','month'),
('04/16/2019','bnxct','90','day'),
('04/17/2019','bnxct','100','day'),
('04/18/2019','bnxct','120','day')
create table #promo
(itemid int,
promo_cost float,
pre_promo_cost float,
promo_start varchar(50),
promo_end varchar(50))
insert into #promo values
('123','214.7','220','10/08/2019','22/08/2019'),
('123','225','230','01/02/2018','15/02/2018'),
('125','400','430','12/08/2019','19/08/2019'),
('125','380','390','15/02/2019','30/02/2019'),
('127','120','140','15/03/2019','30/03/2019'),
('129','80','100','15/04/2019','30/04/2019'),
('129','110','120','01/04/2019','10/04/2019'),
('131','80','100','01/02/2019','15/02/2019'),
('131','110','120','10/01/2019','15/01/2019'),
('133','230','420','10/01/2019','15/01/2019'),
('135','250','440','10/01/2019','15/01/2019'),
('137','270','460','10/01/2019','15/01/2019'),
('139','290','480','10/01/2019','15/01/2019'),
('141','310','500','10/01/2019','15/01/2019'),
('143','330','520','10/01/2019','15/01/2019'),
('145','350','540','10/08/2019','22/08/2019')
create table #output
(itemid int,
available int,
expected date,
isnotsellable int,
pid int,
vendor_id varchar(50),
vendorname varchar(50),
lastconfirmedasin varchar(50),
pageviewsperday int,
promoavg float,
cost float,
price float,
[power] int,
[priority] int)
insert into #output values
('151','1',NULL,'0','15','211','chiran','','0','0','30','50','0','1'),
('127','1',NULL,'0','1','201','cola','klbnm','750','6.3','60','80','60000','1'),
('125','2','08/05/2019','0','1','201','cola','','0','0','430','60','0','2'),
('143','1',NULL,'0','11','210','falon','','0','0','60','80','0','1'),
('145','1',NULL,'0','11','210','falon','','0','0','540','90','0','2'),
('149','1',NULL,'0','11','210','falon','','0','0','20','40','0','3'),
('137','1',NULL,'0','8','207','fill','bnxct','103','65.73','120','140','14420','1'),
('139','1',NULL,'0','8','207','fill','','0','0','30','50','0','2'),
('141','1',NULL,'0','8','207','fill','','0','0','40','60','0','3'),
('131','1',NULL,'0','2','203','foam','werat','700','30.16','70','90','63000','1'),
('135','1',NULL,'0','7','206','JINCO','vbsdx','2050','76','110','130','266500','1'),
('153','1',NULL,'0','16','206','JINCO','','0','0','40','60','0','2'),
('161','2','08/03/2019','0','20','218','sulps','','0','0','60','80','0','1')
Code tried:
; WITH firstsel AS (
SELECT itemid, available, expected, isnotsellable, pid, vendor_id
FROM #productdetail
WHERE available = 1
AND isnotsellable = 0
UNION ALL
SELECT itemid, available, expected, isnotsellable, pid, vendor_id
FROM #productdetail
WHERE available = 2
AND isnotsellable = 0
AND expected <= '20190805'
), addvendorid AS (
SELECT fs.itemid, fs.available, fs.expected, fs.pid, fs.isnotsellable,
coalesce(fs.vendor_id, p.vendor_id) AS vendor_id
FROM firstsel fs
JOIN #product p ON fs.pid = p.id
), asinnumbered AS (
SELECT item_id, lastconfirmedasin, row_number() OVER (PARTITION BY item_id ORDER BY lastconfirmedasin DESC) AS rowno
FROM #asin
)
SELECT av.itemid, av.available, av.expected, av.isnotsellable, av.pid,
av.vendor_id, v.vendorname, an.lastconfirmedasin,
isnull(pv.pageviews, 0) AS pageviews, isnull(p.promoavg, 0) AS promoavg
FROM addvendorid av
JOIN #vendor v ON av.vendor_id = v.vendor_id
LEFT JOIN (asinnumbered an
JOIN (SELECT lastconfirmedasin, SUM(pageviews) AS pageviews
FROM #pageviews
GROUP BY lastconfirmedasin) AS pv ON an.lastconfirmedasin = pv.lastconfirmedasin)
ON an.item_id = av.itemid
AND an.rowno = 1
LEFT JOIN (SELECT itemid, avg((pre_promo_price-promo_price)/promo_price*100) AS promoavg
FROM #promo
GROUP BY itemid) AS p ON p.itemid = av.itemid
ORDER BY av.itemid

How to use equal and not equal together in SQL Server

I have to select values from three tables. First table is sale_project_detail, the second table is design_project_detail, and the third table is design_designer.
sale_project_detail schema:
Id int,
Name nvarchar(50),
ShortDescription nvarchar(max)
design_project_assignment schema:
Id int,
DId int (It is foreign key of design_designer table),
SPId int (It is foreign key of sale_project_detail table),
AssignDateTime datetime,
DueDate date,
Status varchar(10)
design_designer schema:
Id int,
Name nvarchar(15)
Now, I have to select complete detail from sale_project_detail
where assign_project_detail.SPId <> sale_project_detail.Id,
and
Select design_designer(Name)
from design_designer
where design_designer.Id = assign_project_detail.DId
I am trying below code, but it is returning wrong result.
My code:
SELECT
sale_project_detail.*,
design_project_assignment.*,
design_designer.Name
FROM
sale_project_detail,
design_project_assignment,
design_designer
WHERE
NOT EXISTS(SELECT NULL
FROM design_project_assignment
LEFT JOIN design_designer ON design_designer.Id = design_project_assignment.DId
WHERE sale_project_detail.Id = design_project_assignment.SPId)
Thanks in advance.
Try this
SELECT
*
FROM
sale_project_detail as spd
inner join design_project_assignment dpa on dpa.spid <> spd.id
inner join design_designer dd on dd.id = dpa.did;

Insert a row in Order table and multiple rows in OrderDetails table via stored procedure

I have five tables named guest, orders, order_details, food, and employees. Their characteristics are as follows:
create table guest
(
guest_id int primary key identity(1,1),
guest_fname nvarchar(50),
national_id int,
mobile nvarchar(50),
nationality_id int
constraint c15
foreign key(nationality_id) references nationality(nationality_id)
)
create table employees
(
emp_id int primary key ,
emp_fname nvarchar(50),
constraint c1
--foreign key(mgr_id) references employees(emp_id),
foreign key(super_id) references employees(emp_id),
)
go
create table food
(
food_id int primary key identity(1,1),
food_name nvarchar(50),
food_price money,
food_desc nvarchar(200),
cat_id int
constraint c5
foreign key(cat_id) references food_categories(cat_id)
)
go
create table orders
(
order_id int primary key identity(1,1),
order_date datetime,
total float,
guest_id int,
emp_id int,
is_paid bit
constraint c6
foreign key(guest_id) references guest(guest_id),
foreign key(emp_id) references employees(emp_id)
)
go
create table order_details
(
order_id int,
food_id int,
price money,
qty int
constraint c7
primary key(order_id,food_id),
foreign key(order_id) references orders(order_id),
foreign key(food_id) references food(food_id)
)
Go
There is a 1-to-M relationship between orders and order_details.
I want to insert a single row into orders and multiple rows into order_details via a stored procedure. Please help me!
Please give me a stored procedure and explain its algorithm to point me in the right direction.
As #thepirat000 points out, you can use a TVP for the order details/line items since you are using SQL Server 2012. Pinal Dave has a great article on TVPs that you may find helpful. Combine the TVP with scalar parameters for order properties.
For example:
-- NOTE: *Not* accounting for order_id in this case - i.e. a new order where
-- order_id is an identity value.
CREATE TYPE [dbo].[order_details_type] AS TABLE
(
food_id int,
price money,
qty int
)
GO
CREATE PROCEDURE [dbo].[usp_insert_order]
(
#order_id int output,
#order_date datetime = NULL,
#total float,
#guest_id int,
#emp_id int,
#is_paid bit = 0,
#details order_details_type readonly
)
AS
BEGIN
SET NOCOUNT ON;
-- TODO: Wrap the inserts into dbo.orders and dbo.order_details in a
-- transaction as desired.
-- TODO: Check that #order_id does not already exist in dbo.orders and
-- dbo.order_details etc.
-- FORNOW: Proceed optimistically. :}
IF #order_date IS NULL
SET #order_date = GETDATE();
INSERT INTO dbo.orders (order_date, total, guest_id, emp_id, is_paid)
VALUES (#order_date, #total, #guest_id, #emp_id, #is_paid);
SET #order_id = SCOPE_IDENTITY();
INSERT INTO dbo.order_details (order_id, food_id, price, qty)
SELECT #order_id, food_id, price, qty
FROM #details;
END
GO
Executing such a stored procedure is pretty straighforward, as you prepare the TVP argument much like you would a table variable:
/*
* Order up!
*/
/* data I added for a quick check
SELECT TOP 1 * FROM dbo.employees;
--emp_id emp_fname
--1 Wendy
SELECT TOP 1 * FROM dbo.guest;
--guest_id guest_fname national_id mobile
--1 Joe 1 619-555-1212
SELECT TOP 2 * FROM dbo.food;
--food_id food_name food_price food_desc
--1 Onion Rings 5.00 Beer-battered onion rings.
--2 Kobe Burger 10.00 Kobe-beef burger.
*/
-- Prepare the order.
DECLARE #order_id int; -- to get on order insert
DECLARE #now datetime = getdate();
DECLARE #order_details order_details_type;
INSERT INTO #order_details
SELECT 1, 5, 1
UNION
SELECT 2, 10, 2;
-- Insert the order.
EXEC dbo.usp_insert_order
#order_id = #order_id OUTPUT,
#order_date=#now,
#total=25,
#guest_id=1,
#emp_id=1,
#is_paid=0,
#details=#order_details;
/*
* Check the order.
*/
SELECT * FROM dbo.orders WHERE order_id = #order_id;
--order_id order_date total guest_id emp_id is_paid
--1 2014-03-13 21:44:45.400 25 1 1 0
SELECT * FROM dbo.order_details WHERE order_id = #order_id;
--order_id food_id price qty
--1 1 5.00 1
--1 2 10.00 2
Another option that pre-dates TVPs may interest you too - using an XML parameter for the order details/line items and scalar parameters for order properties. Related resources and examples abound.
A variation of the XML-param approach that is to pass XML for the order and its details/line items; but I think this is overkill personally.
you need 2 store procs, 1 for order and 1 for Order_details, in the last one add update statement for food table qty. you do not want to make 1 sproc for all

SQL query Optimization help

I have the the following SQL query
Declare #tempcalctbl Table
(
ItemId varchar(50),
ItemLocation varchar(50),
ItemNo varchar(50),
Width real,
Unit varchar(50),
date datetime
)
Insert Into #tempcalctbl
Select distinct SubId,ItemLocation,ItemNo,
(ABS((Select width From #temptbl a Where ItemProcess ='P1'and a.ItemId = c.ItemId
and a.ItemNo = c.ItemNo and a.ItemLocation = c.ItemLocation)
-(Select width From #temptbl b Where ItemProcess ='P2' and b.ItemId = c.ItemId
and b.ItemNo = c.ItemNo and b.ItemLocation = c.ItemLocation))) * 1000,
Unit,date
From #temptbl c
Group by ItemId,ItemLocation,ItemNo,Unit,date
I was wondering how to optimize this query.
The idea is to find out the different in width (p1's item - p2's item) between ItemProcess 'P1' and 'P2' according to the same ItemID, same ItemNo and same ItemLocation.
I have around 75000 and it took more then 25 minute to get the width differences for all the ItemId.
I tried to use Group by for the width different calculation but it would return multiple row instead of just a value which then would return error. By the way I am use MS SQL server 2008 and #tempcalctbl is a table that I declared in a store procedure.
Does the following help?
INSERT INTO #tempcalctbl
SELECT P1.SubId ,
P1.ItemLocation ,
P1.ItemNo ,
ABS(P1.Width - P2.Width) * 1000 AS Width ,
P1.Unit ,
P1.date
FROM #temptbl AS P1
INNER JOIN #temptbl AS P2 ON P1.ItemId = P2.ItemId
AND P1.ItemNo = P2.ItemNo
AND P1.ItemLocation = P2.ItemLocation
WHERE P1.ItemProcess = 'P1'
AND P2.ItemProcess = 'P2'
EDIT
To make use of indexes, you will need to change your table variable to a temporary table
CREATE TABLE #temptbl
(
ItemId varchar(50),
ItemLocation varchar(50),
ItemNo varchar(50),
Width real,
Unit varchar(50),
date DATETIME,
ItemProcess INT,
SubId INT
)
CREATE NONCLUSTERED INDEX Index01 ON #temptbl
(
ItemProcess ASC,
ItemId ASC,
ItemLocation ASC,
ItemNo ASC
)
INCLUDE ( SubId,Width,Unit,date)
GO
That should speed you up a little.
John Petrak's answer is the best query for this case.
If the speed is still now acceptable, maybe you can store #temptbl at a temporary real table, and create the related index on those four columns.