Finding Related Items
Jun 7, 2007
I was thinking last night of restructuring the way "Related Items" are pulled from the database for one of our sites. Basically at the moment it is upto the client to flag two products as related. I'm thinking of using a new method of tagging the products and then finding related products based on the tags assigned -the general code for this is below but what I want to know is, is using "IN" the most efficient way of doing this?
TIA
Tim
DECLARE @ItemId int
SET @ItemId = 1
SELECT
COUNT(i.ItemId) AS MatchingTags,
i.ItemId,
i.ItemName
FROM
tst_Items i LEFT JOIN txt_x_Items_Tags x
ON i.ItemId = x.ItemId
WHERE
x.TagId IN (
SELECT
t.TagId
FROM
tst_Tags t LEFT JOIN txt_x_Items_Tags x
ON t.TagId = x.TagId
WHERE
x.ItemId = @ItemId
)
GROUP BY
i.ItemId,
i.ItemName
HAVING
i.ItemId <> @ItemId
ORDER BY
MatchingTags DESC
The testing data:
CREATE TABLE [dbo].[tst_Items](
[ItemId] [int] NOT NULL,
[ItemName] [nvarchar](50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[tst_Tags](
[TagId] [int] NOT NULL,
[TagName] [nvarchar](50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[txt_x_Items_Tags](
[ItemId] [int] NOT NULL,
[TagId] [int] NOT NULL
) ON [PRIMARY]
GO
INSERT INTO tst_Items VALUES (1, 'Test Item 1')
INSERT INTO tst_Items VALUES (2, 'Test Item 2')
INSERT INTO tst_Items VALUES (3, 'Test Item 3')
INSERT INTO tst_Items VALUES (4, 'Test Item 4')
INSERT INTO tst_Tags VALUES (1, 'Tag 1')
INSERT INTO tst_Tags VALUES (2, 'Tag 2')
INSERT INTO tst_Tags VALUES (3, 'Tag 3')
INSERT INTO tst_Tags VALUES (4, 'Tag 4')
INSERT INTO txt_x_Items_Tags VALUES (1, 1)
INSERT INTO txt_x_Items_Tags VALUES (1, 2)
INSERT INTO txt_x_Items_Tags VALUES (1, 3)
INSERT INTO txt_x_Items_Tags VALUES (2, 1)
INSERT INTO txt_x_Items_Tags VALUES (2, 3)
INSERT INTO txt_x_Items_Tags VALUES (3, 1)
INSERT INTO txt_x_Items_Tags VALUES (3, 2)
INSERT INTO txt_x_Items_Tags VALUES (1, 4)
INSERT INTO txt_x_Items_Tags VALUES (4, 4)
GO
----------------------------
I've finally started blogging (all be it badly!)
Check it out:
http://blogs.thesitedoctor.co.uk/tim/
View 1 Replies
ADVERTISEMENT
Jan 11, 2006
Hey guys,
I have created an asp.net page where users can select multiple items and then submit the form. I would like to return related items back. The catch is, I want to only return items that are related to all of the selected items.
I've created a SQL Procedure that puts each of the inputted item's ItemId in to a temp table, I have a second table called RelatedItems which I use as my junction table that has ItemId, and ReleatedItemId, I then have my Item table that has the data I want to get to (I've excluded this because I have no trouble pulling out data once I have an ItemId)
I can pull out all related ItemIds with a simple join, however I don't know where to start when it comes to pulling out only items related to all ItemIds in the @TempTable.
Any help or suggestions would be great.
Thanks,
Matt
View 1 Replies
View Related
May 28, 2008
Hi,
1.
Right now in my queries I am using lots of LEFT Joins and INNER JOINs... and I was suggested to look at 'IN'... But with IN I did face some performance issues previously and stopped using it... but I have got new doubts on which query will give me better performance...
A query using LEFTJoin or a query using IN/NOT-IN
2.
This question is about CONVERT...
I have a stored proc which is used for updating a table... and multiple columns [of the same table] and corresponding values are sent to the proc [only a subset of the columns might be sent for updates everytime and the columns to update is not fixed for each run of the SP]...
I have to construct a UPDATE String out of it using string concatenation to finally be able to use "sys.sp_executesql" on that update statement...
This results in me having to use CONVERT() lots of times... and one of the columns among them on which I am doing a CONVERT is of the type XML...
So the question is as follows...
a. Is it preferrable to construct a single UPDATE statement string and execute it using "sys.sp_executesql"
b. Or Is it preferrable to give multiple UPDATE statments... i.e. one update statement for each column [Depending on whether that column has to be updated for that run or not]
i.e. The question essentially is:
Does a single update query constructed using lots of CONVERTS [Basically on INT and XML types]
give more performance over using multiple UPDATE statments on the table
Or is it the other way round..
Thanks,
Pratap.
View 5 Replies
View Related
Aug 25, 2014
I am creating a report that will identify the website categories that our items are in. The purpose is to find items that are not in categories that they should be so they can be fixed. Attached is a csv of a subset of the data.
The data I attached has all of our Baskets by SKU (ItemNoSKU) and the associated web categories that those items are in. For example, we can see that ItemNoSKU AB107 is in web categories 4, 22, and 23.
What I have already done is get a Total Baskets vs Web Cat Baskets. I know the total baskets is 44:
Code:
SELECT MerchCatDesc, MerchSubCatDesc, COUNT(DISTINCT ItemNoSKU)
FROM myTable
GROUP BY MerchCatDesc, MerchSubCatDesc
And I know the number of baskets in WebCat 23 is 43:
Code:
SELECT WebCatCd,MerchCatDesc, MerchSubCatDesc, COUNT(DISTINCT ItemNoSKU)
FROM myTable
GROUP BY WebCatCd, MerchCatDesc, MerchSubCatDesc
So in this instance, I know there is 1 Basket ItemNoSKU that is not in WebCatCd 23. I need to list this "missing" ItemNoSKU along with the WebCatCd it is missing from. I am struggling on how to write the code to accomplish this for my full list of many categories and web categories.
View 11 Replies
View Related
Apr 2, 2008
Hi, I need to write a query which I have never attempted before and could do with some help.... I have a Groups table and a Users_Groups look up table. In this model, users can only be assigned to 1 group. If a group is deleted, a trigger should fire and delete any rows in User_Groups having a matching Groups.Ref. Unfortunately, the trigger hasn't been firing and I now have a load of defunct rows in Users_Groups relating users to groups which do not exist.I now need to find all of these defunct rows in Users_Groups so that I can delete them. How can I find rows in Users_Groups where the parent rows and refs in Groups are null? I've tried searching the net for something similar but don't even know how to word the search properly to get any half relevant results. Cheers PS, I do realise I need to tighten the constraints on my database
View 5 Replies
View Related
Apr 17, 2007
Hi: I'm try to create a stored procedure where I sum the amounts in an invoice and then store that summed amount in the Invoice record. My attempts at this have been me with the error "The multi-part identifier "items.TAX" could not be bound"Any help at correcting my procedure would be greatly appreciate. Regards,Roger Swetnam ALTER PROCEDURE [dbo].[UpdateInvoiceSummary] @Invoice_ID intAS DECLARE @Amount intBEGIN SELECT Invoice_ID, SUM(Rate * Quantity) AS Amount, SUM(PST) AS TAX FROM InvoiceItems AS items GROUP BY Invoice_ID HAVING (Invoice_ID = @Invoice_ID) Update Invoices SET Amount = items.Amount WHERE Invoice_ID =@Invoice_IDEND
View 3 Replies
View Related
Feb 25, 2015
I am struggling to come up with a set-based solution for this problem (i.e. that doesn't involve loops/cursors) ..A table contains items (identified by an ItemCode) and the set they belong to (identified by a SetId). Here is some sample data:
SetIdItemCode
1A
1B
24
28
26
310
312
410
[code]....
You can see that there are some sets that have the same members:
- 1 and 10
- 2 and 11
- 7, 8 & 9
What I want to do is identify the sets that have the same members, by giving them the same ID in another column called UniqueSetId.
View 8 Replies
View Related
Apr 10, 2015
I'm having an issue creating a report that can group & sum similar items together (I know in some ways, the requirement doesn't make sense, but it's what the client wants).
I have a table of items (i.e. products). Â In some cases, items can be components of another item (called "Kits"). Â In this scenario, we consider the kit itself, the "parent item" and the components within the kit are called "child items". Â In our Items table, we have a field called "Parent_Item_Id". Â Records for Child Items contain the Item Id of the parent. Â So a sample of my database would be the following:
ItemId | Parent_Item_Id | Name | QuantityAvailable
----------------------------------------
1 | NULL | Kit A | 10
2 | 1 | Item 1 | 2
3 | 1 | Item 2 | 3
4 | NULL | Kit B | 4
5 | 4 | Item 3 | 21
6 | NULL | Item 4 | 100
Item's 2 & 3 are child items of "Kit A", Item 5 is a child item of "Kit B" and Item 6 is just a stand alone item.
So, in my report, the client wants to see the SUM of both the kit & its components in a single line, grouped by the parent item. Â So an example of the report would be the following:
Name | Available Qty
--------------------------
Kit A | 15
Kit B | 25
Item 4 | 100
How I can setup my report to group properly?
View 6 Replies
View Related
May 12, 2006
I cannot find an easy way to DELETE items which are > 1 time in my table (i am working with MS SQL 2000)
idserialisOk
-------------------
2AAA1
3BBB0
5dfds0
6CCC1
7fdfd 0
8AAA0
9CCC0
I want to DELETE each Row IN
SELECT doublons.serial, Count(doublons.serial) AS 2Times
FROM doublons
GROUP BY doublons.serial
HAVING Count(doublons.serial)>1
and WHERE isOK = 0
in my exemple , after deleting, my table must look like
idserialisOk
-------------------
8AAA1
9CCC1
3BBB0
5dfds0
7fdfd0
thank you for helping
View 10 Replies
View Related
Mar 20, 2008
Hi thanks for looking at my question
Using sqlServer management studio 2005
My Tables are something like this:
--Table 1 "Employee"
CREATE TABLE [MyCompany].[Employee](
[EmployeeGID] [int] IDENTITY(1,1) NOT NULL,
[BranchFID] [int] NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[MiddleName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[EmployeeGID]
)
GO
ALTER TABLE [MyCompany].[Employee]
WITH CHECK ADD CONSTRAINT [FK_Employee_BranchFID]
FOREIGN KEY([BranchFID])
REFERENCES [myCompany].[Branch] ([BranchGID])
GO
ALTER TABLE [MyCompany].[Employee] CHECK CONSTRAINT [FK_Employee_BranchFID]
-- Table 2 "Branch"
CREATE TABLE [Mycompany].[Branch](
[BranchGID] [int] IDENTITY(1,1) NOT NULL,
[BranchName] [varchar](50) NOT NULL,
[City] [varchar](50) NOT NULL,
[ManagerFID] [int] NOT NULL,
CONSTRAINT [PK_Branch] PRIMARY KEY CLUSTERED
(
[BranchGID]
)
GO
ALTER TABLE [MyCompany].[Branch]
WITH CHECK ADD CONSTRAINT [FK_Branch_ManagerFID]
FOREIGN KEY([ManagerFID])
REFERENCES [MyCompany].[Employee] ([EmployeeGID])
GO
ALTER TABLE [MyCompany].[Branch]
CHECK CONSTRAINT [FK_Branch_ManagerFID]
--Foreign IDs = FID
--generated IDs = GID
Then I try a simple single row DELETE
DELETE FROM MyCompany.Employee
WHERE EmployeeGID= 39
Well this might look like a very basic error:
I get this Error after trying to delete something from Table €œEmployee€?
The DELETE statement conflicted with the
REFERENCE constraint "FK_Branch_ManagerFID".
The conflict occurred in database "MyDatabase",
table "myCompany.Branch", column 'ManagerFID'.
Yes what I€™ve been doing is to deactivate the foreign key constraint, in both tables when performing these kinds of operations, same thing if I try to delete a €œBranch€? entry, basically each entry in €œbranch€? and €œEmployee€? is child of each other which makes things more complicated.
My question is, is there a simple way to overcome this obstacle without having to deactivate the foreign key constraints every time or a good way to prevent this from happening in the first place? Is this when I have to use €œON DELETE CASCADE€? or something?
Thanks
View 8 Replies
View Related
Nov 23, 2004
Hi,
Is there a format function in MDX which will help me solve the following
scenario:
One of my measures is Net Sales and I have tried all different formats
in Analysis Services so that it shows without the decimal places i.e.
instead of showing the Net Sales for any selected combination of
Dimensions as 123,456.04, I want to show it as 123,456
When I browse the cube (in Analysis Services), I can meet my
requirement. However, in my front-end (Microsoft Data Analyzer), I am
still getting it as 123,456.04 (even when the same in Analysis services,
i.e. when I browse the cube, is being shown as 123,456).
I do not have much choice at the moment and am stuck with Microsoft Data
Analyzer and unfortunately have not been able to solve this :(
Can someone think of a solution/workaround/use of MDX which will help me
get the results being displayed without the decimal. Is there a format function that I can use in MDX and how to use it???
Many TIA
View 2 Replies
View Related
Aug 5, 2006
Hello,What is uniqueidentifier as a data type?Also what is the data type for setting unique STRINGS ((nchar,nvarchar), for example to be used for emails and user names in a userregistration system).SQL Server does not allow me set primary keys for columns where datatypes are not INT.Thanks in advance.
View 3 Replies
View Related
May 4, 2006
t1
order
item
how can i get the order that has less than 2 items?
View 6 Replies
View Related
Nov 20, 2006
I've been working on a performance review web application (i.e., employee's annual reviews done via the web). In the process of creating the application I've been teaching myself .NET - maybe not the best way to do it but I've been learning a lot. However, I still feel like I'm not doing something right.On each Page_Load I'm doing database work with a data reader: Reading the data in, displaying it, letting the user add, edit, or delete it, etc. So every Page_Load code behind looks like this: string sql = "SELECT UserID, Passwd, RecID, Name FROM UserList";
SqlConnection myConn = new SqlConnection("Server=BART; Database=WSSD; User ID=sa; Password=wss1231");
SqlCommand cmd = new SqlCommand(sql, myConn);
SqlDataReader dr;
myConn.Open();
dr = cmd.ExecuteReader(); And so forth and so on. Now since I re-use this code again and again - I imagine it's a good idea to implement my connection code in a class that I can re-use easily. But I have no idea where to start on something like that. What can I say? I'm a newb. A push in the right direction would be great.
View 8 Replies
View Related
Jan 5, 2008
I have the following tablestblUserdatausercode username firstname lastname5 peter peter smith11 john433 john doe15 simonsays Simon SmithtblEventsID postedbycode title eventtext createdate1 5 woodstock 'oldies' 12/12/20082 11 love parade 'dance all night 1/1/20083 11 spring break 'great party' 2/2/2006tblEventVisitorsusercode eventid5 15 311 111 211 3As you can see User John433 is going to 3 events.But I only want to select the one that has the first upcoming startdate bigger than now: getdate()Desired output would be:username firstname lastname eventid title eventtext eventdatepeter Peter Smith 1 woodstock 'oldies' 12/12/2008john433 john doe 2 love parade 'dance all night 1/1/2008simonsays Simon Smith NULL NULL NULL NULLHow can I make such a selection? (perhaps see this thread for similar info: http://forums.asp.net/t/1201266.aspx)Thanks!
View 16 Replies
View Related
Feb 12, 2008
I want to make simple database application but I want that I make just one transaction with the database..
If I have , say 10 insert queries, i want to transact with the database just once.
Somebody told me this could be done by 'containers' or 'data transfer objects'
So please, somebody help..
View 1 Replies
View Related
Mar 10, 2005
Hi,
I made a DTS which appends data coming infrom a view to an exisiting table.So far no problem and all goes well.
I am facing a problem due to the format of the date that is coming in (getting appended) and while going through BOL, came across the following topic:
mk:@MSITStore:C:Program%20FilesMicrosoft%20SQL%2 0Server80ToolsBookshowtosql.chm::/ht_dts_trns_97ou.htm
I tired the above tips but it appears that if I try to do this in my DTS (which appends data),the logic of the DTS will change. A single arrow also gets added whichI think represents a simple mapping/transformation rather than a append. To clarify my point, please note the attached image which represents that the data is being appended (due to the many sided arrows pointing to the source and destination - visible under the Transformations tab of my DTS).
Sincerely hoping that my post is clear, can someone help me find how to make changes in a DTS (which appends data) and ensuring that thelogic remains the same i.e. it should append data.
Many TIA
View 4 Replies
View Related
Jul 24, 2007
I have a function written in postgresql that I want to create in sql server (UDF). After effort of full day I am seding this request to please help me, here is the function:
CREATE OR REPLACE FUNCTION fn_comma_env(int4)
RETURNS text AS
$BODY$
DECLARE
rec record;
str text;
comstr text;
BEGIN
str := '';
comstr := '';
FOR rec IN SELECT class.classname FROM hostenv, class WHERE hostenv.classid = class.classid AND (hostenv.hostid = $1) LOOP
str := str || comstr || rec.classname;
comstr := ',';
END LOOP;
RETURN str;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
Thanks in advance,
Syed
View 1 Replies
View Related
Jun 20, 2008
select @xml = bulkcolumn from openrowset(bulk 'C:Documents and
SettingsKasiDesktopewsrss.xml' , single_blob) as channel
here after bulk instead of giving path, we have to give parameter so that the paramter takes the value from the table.
the tables contains paths of xml files
View 2 Replies
View Related
Jan 4, 2006
there is a prblem with data in pivoting the table.
problem is like this--
there is some data 'xy' and some data 'xy '. when i m giving 'xy' as a pivot key value it doesent recognise 'xy ' and viseversa..
i can't reduce the size of the datatype coz there is some data of diffrent size as 'abcd'.
this data is loaded from excel sheet to sql sever table.
wht can i do for this problem.
is there any method to truncate the indivisual data, i m using nvarchar datatype for this.
View 2 Replies
View Related
Jan 12, 2007
Hi friends,
I am backing up the database using the Database Maintenance Plan.
Everything is in place. I want to save the file name in the format yyyy-mm-dd_finbck.bak. how can i assign the date from here itself ? this should be done through the DB maintenance plan only.
is it possible ? can we assign the date to the backup file through the DB maintenence plan ?
kindly guide.
Regards,
Amit
View 4 Replies
View Related
Dec 10, 2007
Dear All,
Could anyone guide me to prepare for the Interview in SQL SERVER 2005.
I have studied the relevant things from background knowledge from the SQL Server books. But is there any specific areas in which I have to concentrate for the sake of Interview?
Thanks in Advance.
View 16 Replies
View Related
Jul 23, 2005
Is it possible to retrieve all tables that a given one is related tovia foreign keys?
View 2 Replies
View Related
Aug 11, 2005
We had been running SQL Server without any control of security (sincethe company is very small -100 employees). All of us know the adminpassword and has been accessing the database as admin. Our databaseserver crashed due to hardware failure twice last month and we lost alot of important data. Now the management is taking the control ofserver access seriously.SQL Enterprise manager is installed on many PCs and any one can deleteany database with a right click.My question is:1. Can the enterprise manager be installed on client's PC with alimited right (or as a user not as admin)?We need to limit the user's access of using the Enterprise Manager.In other words, how can we set this up for different users.2. How can we keep running SQL Server if one server fails?Clustering or Replication or Mirroring? OI would highly appreciate if you could direct me to any website orresources on how to set up security of SQL Server (2000 with the latestservice pack).Thanks a million in advance.Best regards,Mamun
View 2 Replies
View Related
Oct 26, 2006
Any idea the cause of this error. I got it while trying to execute a stored proc (in sql 2005). I had just restored database and below error is stucking me to move ahead. Any help please
Error invoking method 'ExecuteQuery' for transaction (Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding)
View 1 Replies
View Related
Jul 25, 2007
I have a function written in postgresql that I want to create in sql server (UDF). After effort of full day I am seding this request to please help me, here is the function:
CREATE OR REPLACE FUNCTION fn_comma_env(int4)
RETURNS text AS
$BODY$
DECLARE
rec record;
str text;
comstr text;
BEGIN
str := '';
comstr := '';
FOR rec IN SELECT class.classname FROM hostenv, class WHERE hostenv.classid = class.classid AND (hostenv.hostid = $1) LOOP
str := str || comstr || rec.classname;
comstr := ',';
END LOOP;
RETURN str;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
Thanks in advance,
Syed
View 1 Replies
View Related
Mar 20, 2008
Hi,
I have a data including "year", "month" and "day" columns and I'm using these columns as parameter to create a report. I'm using the parameters successfully in my report. I import all possible year-month-day combinations but in my data there are some unmatched combinations. (For ex, for 2007 there's just last 3 months of the year, and some days are missing) To make the report more affective, I wanna make the parameters dynamic; when I choose 2007 in year-combobox I wanna see just the related months (not all 12) and the related days after I choose the month. Is it possible in reporting services?
View 9 Replies
View Related
Jun 22, 2004
Hi,
I'm trying to include the COUNT(*) value of a sub-query in the results of a parent query. My SQL code is:
SELECT appt.ref, (Case When noteCount > 0 Then 1 Else 0 End) AS notes FROM touchAppointments appt, (SELECT COUNT(*) as noteCount FROM touchNotes WHERE appointment=touchAppointments.ref) note WHERE appt.practitioner=1
This comes up with an error basically saying that 'touchAppointments' isn't valid in the subquery. How can I get this statement to work and return the number of notes that relate to the relevant appointment?
Cheers.
View 6 Replies
View Related
May 13, 2008
Hey everyone,
I'm working on a document management system that will allow the users to tag docs. Would it better in terms of performance and general maintenance to have all the tags comma de-limited in a column of the doc record, or have each tag in a row of an associated table?
Thanks in advance!
View 3 Replies
View Related
Aug 22, 2014
how can run a query that would not list duplicate e.g.
item 1 section 1
item 2 section 1
item 3 section 1
item 4 section 1
item 5 section 2
item 6 section 2
item 7 section 3
the output would be
section 1
section 2
section 3
View 1 Replies
View Related
Oct 3, 2007
how to find which items from a list (without using table ) are not in a specific table
('443',
'470',
'878',
'567',
'430'
)
problem is the following query gives what is in the table
select distinct areacode
from area_code
where areacode
in
('443',
'470',
'878',
'567',
'430'
)
tried using count to see 0 but only get 1 .... N
don't want to create a table everytime ... for dynamic list
TIA
View 1 Replies
View Related
Jun 25, 2007
Hello Experts. You may have more luck at this than me.
I am interested in finding the quantity of items that were ordered alone. I have an orderid field and a product field. So the count of the orderid has to equal one and the have them grouped by product.
Example of how data looks like
I am looking for transactions like orderid 3 and 5.
OrderID
Product
1
hotdog
1
burger
1
taco
2
burrito
2
snack
2
chips
3
burger
4
hotdog
4
burger
4
taco
5
burrito
6
snack
6
chips
When i run
SELECT product, count(orderid)
From Table
Where BusinessDateID = 20060725
group by product
having (count(orderid)=1)
I only get back items that were only sold once.
I am looking for a result that looks like this
Product
Ordered alone
hotdog
2
burger
3
taco
4
burrito
32
snack
12
chips
76
View 7 Replies
View Related
Mar 24, 2004
Hi all,
I am trying to insert user's input from a web form into the tables. For example,
PURCHASE TABLE(PurchaseID, PurchaseNo, Date, PartID)
PART TABLE(PartID, PartDescription,MachineID)
MACHINE TABLE(MachineID, MachineName)
On the web form I have textboxes for the Purchase No., date and part description, and a drop down list for the machine name. How do I insert them into the different tables?
I've just start learning ASP.NET and I am using Web Matrix for this. The examples I've seen so far only shows how to insert into a single table.
Thanks!
View 2 Replies
View Related