Query for matching multiple rows? - sql

We have next tables in our system
Table object
object_id object_description
1 "Car"
2 "Person"
Table attribute
attribute_id attribute_name
1 "hair_color"
2 "height"
3 "number_of_doors"
4 "engine_size"
Table attribute_value
attribute_id attribute_value_id value
1 1 "black"
1 2 "blonde"
2 1 "more than 1 meter"
2 2 "less than 1 meter"
3 1 "5 doors"
3 2 "3 doors"
4 1 "more than 1.9"
4 2 "less than 1.9"
Table object_attribute
object_id attribute_id attribute_value_id
1 3 1 -- Car, number of doors,5
1 3 2 -- Car, number of doors,2
1 4 1 -- Car, engine size, greater than 1.9
1 4 2 -- Car, engine size, less than 1.9
With this structure we are having a lot of problems getting objects that match multiple criterias (i.e. get all cars with 3 doors and engine size bigger than 1.9)
Currently we are using INTERSECTS for doing this
SELECT OBJECT_ID
FROM object_attribute
WHERE attribute_id = 3
AND attribute_value = 2
INTERSECT
SELECT OBJECT_ID
FROM object_attribute
WHERE attribute_id = 4
AND attribute_value = 1
There are diferent objects with diferent number of attributes, so we can't use a fixed number of JOINs or INTERSECTs anymore
Is there any way of generate multiple combinations of all attributes in a "dynamic way"?
What we would like to achieve is a dynamic query that builds a view like this:
object_id | att_name_1 | att_value_1 | att_name_2 | att_value2 | att_name_n | attr_value_n
As the number of attributes is variable we should trigered and update of the query when a new object is inserted
Guys I think what I have in mind is not possible, so we will probably go with this dynamic query construction at runtime. Thank you all for your answers

after some tests i came up with the following query:
select distinct
a.attribute_name, o.object_description, av.value,
oa.attribute_id, oa.object_id, oa.attribute_value_id
from object_attribute oa
inner join attribute a on (oa.attribute_id = a.attribute_id and a.attribute_id = 3)
inner join object o on (oa.object_id = o.object_id and o.object_id = 1)
inner join attribute_value av on (oa.attribute_value_id = av.attribute_value_id and av.attribute_value_id = 2)
where
(av.attribute_id = 3 and o.object_id = 1 and av.attribute_value_id = 2)
union
select distinct
a.attribute_name, o.object_description, av.value,
oa.attribute_id, oa.object_id, oa.attribute_value_id
from object_attribute oa
inner join attribute a on (oa.attribute_id = a.attribute_id and a.attribute_id = 4)
inner join object o on (oa.object_id = o.object_id and o.object_id = 1)
inner join attribute_value av on (oa.attribute_value_id = av.attribute_value_id and av.attribute_value_id = 1)
where
(av.attribute_id = 4 and o.object_id = 1 and av.attribute_value_id = 1)
which results in the following:
If you are using MS SQL Server I would put it in a stored procedure that accepts the three Id's as parameters.

Related

SELECT from 2 differents tables

I would like to select all possible brands for different products where the fk_category_id is for example equal to "2".
produits :
id titre fk_category_id fk_marque_id is_active is_delete
1 Swoke 2 1 1 0
2 Café 2 2 1 0
3 Fraise 2 3 1 0
4 Fruits 2 4 1 0
manufacturers :
id name
1 Swoke
2 Liqua
3 Alfaliquid
4 TJuice
5 otherBrands
I already tried a lot of things and for example this request :
SELECT m.name, m.id, p.fk_category_id
FROM produits p
INNER JOIN manufacturers m
WHERE p.fk_category_id = 2
AND p.is_active = 1
AND p.fk_marque_id = m.id
AND p.is_delete = 0;
But it doesn't works.
The expected result is :
result :
id name
1 Swoke
2 Liqua
3 Alfaliquid
4 TJuice
It's the same as the table "manufacturers" but I have to sort by fk_category_id because I only want the brand with the fk_category = 2.
So if someone could explain me or help me to understand how to solve my "problem" ? Thanks you in advance, I continue my research by my side :).
If you need something else i can give you anything.
I think what you need to do is have a condition on your join, to say how the data from the 2 table should join together.
On the assumption that fk_marque_id is your reference in produits to an item in manufacturers (assumed from looking at your where clause), your sql could look like this:
SELECT
p.id, p.titre, m.name, m.id, p.fk_category_id
FROM
produits p
INNER JOIN manufacturers m ON p.fk_marque_id = m.id
WHERE p.fk_category_id = 2
AND p.is_active = 1
AND p.is_delete = 0;
The naming convention of your fields in produits is a little weird however, if one of the the FK fields is a link to an ID in manufacturers. You'd normally expect to see something like FK_manufacturers_Id so it's clear that this column is the reference to that field (Id) in that table (manufacturers)
If you are just looking to join products and manufacturers table where fk_category_id = 2, it can be done something like this
SELECT m.id, m.name
FROM manufacturers m
INNER JOIN produits p
ON m.id = p.fk_marque_id
WHERE p.fk_category_id = 2
AND p.is_active = 1
AND p.is_delete = 0;

SQL Code to get results when there are no records in a table

There are 4 tables (user, user options, option type 1, and option type 2). The user table is not directly involved here but mentioned for completeness. Here are the table columns for each of the involved tables.
User Options:
UserID,
Option1ID,
Option2ID,
Option1:
Option1ID,
Option1Description
Option2:
Option2ID,
Option2Description
All the values for Option1 can be combined with all the values for Option2 hence if there a 'x' number of Option1 values and 'y' number of Option2 values then the resultant number of option combinations is 'x' * 'y'. I want to write a query such that it will always result in 'x' * 'y' rows for a given UserID even if there is no record for a particular combination of Option1ID and Option2ID for that user in the UserOptions table. Additionally there should be a column that indicates if the particular combination of Option1 and Option2 exists in the UserOptions table.
Option1
Option1ID Option1Description
----------------------------------
1 1_Description1
2 1_Description2
Options2
Option2ID Option2Description
----------------------------------
1 2_Description1
2 2_Description2
UserOptions
UserID Option1ID Option2ID
---------------------------------
1 1 2
1 2 2
Result
UserID Option1ID Option2ID Exists
----------------------------------------------
1 1 1 0
1 1 2 1
1 2 1 0
1 2 2 1
Given the above what would the SQL query be? In addition note that UserID = 2 does not exist in the UsersOptions table. In this case the query should still return 4 records where the UserID column will always be 2, the OptionID columns will be the same, and the Exists column will always be 0.
You can cross join the users table with the two options tables to generate all possible combinations, then search for a match in bridge table useroptions with a left join:
select u.userid, o1.option1id, o2.option2id,
case when uo.userid is null then 0 else 1 end as uo_exists
from users u
cross join option1 o1
cross join option2 o2
left join useroptions uo
on uo.userid = u.id
and uo.option1id = o1.option1id
and uo.option2id = o1.option2id
You could also use exists instead of a left join:
select u.userid, o1.option1id, o2.option2id,
case when exists (
select 1
from useroptions uo
where uo.userid = u.id and uo.option1id = o1.option1id and uo.option2id = o1.option2iduo.userid
) then 1 else 0 end as uo_exists
from users u
cross join option1 o1
cross join option2 o2

Is there a simpler way to write this query? [MS SQL Server]

I'm wondering if there is a simpler way to accomplish my goal than what I've come up with.
I am returning a specific attribute that applies to an object. The objects go through multiple iterations and the attributes might change slightly from iteration to iteration. The iteration will only be added to the table if the attribute changes. So the most recent iteration might not be in the table.
Each attribute is uniquely identified by a combination of the Attribute ID (AttribId) and Generation ID (GenId).
Object_Table
ObjectId | AttribId | GenId
32 | 2 | 3
33 | 3 | 1
Attribute_Table
AttribId | GenId | AttribDesc
1 | 1 | Text
2 | 1 | Some Text
2 | 2 | Some Different Text
3 | 1 | Other Text
When I query on a specific object I would like it to return an exact match if possible. For example, Object ID 33 would return "Other Text".
But if there is no exact match, I would like for the most recent generation (largest Gen ID) to be returned. For example, Object ID 32 would return "Some Different Text". Since there is no Attribute ID 2 from Gen 3, it uses the description from the most recent iteration of the Attribute which is Gen ID 2.
This is what I've come up with to accomplish that goal:
SELECT attr.AttribDesc
FROM Attribute_Table AS attr
JOIN Object_Table AS obj
ON obj.AttribId = obj.AttribId
WHERE attr.GenId = (SELECT MIN(GenId)
FROM(SELECT CASE obj2.GenId
WHEN attr2.GenId THEN attr2.GenId
ELSE(SELECT MAX(attr3.GenId)
FROM Attribute_Table AS attr3
JOIN Object_Table AS obj3
ON obj3.AttribId = attr3.AttribId
WHERE obj3.AttribId = 2
)
END AS GenId
FROM Attribute_Table AS attr2
JOIN Object_Table AS obj2
ON attr2.AttribId = obj2.AttribId
WHERE obj2.AttribId = 2
) AS ListOfGens
)
Is there a simpler way to accomplish this? I feel that there should be, but I'm relatively new to SQL and can't think of anything else.
Thanks!
The following query will return the matching value, if found, otherwise use a correlated subquery to return the value with the highest GenId and matching AttribId:
SELECT obj.Object_Id,
CASE WHEN attr1.AttribDesc IS NOT NULL THEN attr1.AttribDesc ELSE attr2.AttribDesc END AS AttribDesc
FROM Object_Table AS obj
LEFT JOIN Attribute_Table AS attr1
ON attr1.AttribId = obj.AttribId AND attr1.GenId = obj.GenId
LEFT JOIN Attribute_Table AS attr2
ON attr2.AttribId = obj.AttribId AND attr2.GenId = (
SELECT max(GenId)
FROM Attribute_Table AS attr3
WHERE attr3.AttribId = obj.AttribId)
In the case where there is no matching record at all with the given AttribId, it will return NULL. If you want to get no record at all in this case, make the second JOIN an INNER JOIN rather than a LEFT JOIN.
Try this...
Incase the logic doesn't find a match for the Object_table GENID it maps it to the next highest GENID in the ON clause of the JOIN.
SELECT AttribDesc
FROM object_TABLE A
INNER JOIN Attribute_Table B
ON A.AttrbId = B.AttrbId
AND (
CASE
WHEN A.Genid <> B.Genid
THEN (
SELECT MAX(C.Genid)
FROM Attribute_Table C
WHERE A.AttrbId = C.AttrbId
)
ELSE A.Genid
END
) -- Selecting the right GENID in the join clause should do the job
= B.Genid
This should work:
with x as (
select *, row_number() over (partition by AttribId order by GenId desc) as rn
from Attribute_Table
)
select isnull(a.attribdesc, x.attribdesc)
from Object_Table o
left join Attribute_Table a
on o.AttribId = a.AttribId and o.GenId = a.GenId
left join x on o.AttribId = x.AttribId and rn = 1

SQL join to table with 3 possible cases: table can have no records, match 1 or more, records or require all records found to match

I have a 2 tables:
Questions table with Question ID
Part Table:
Question ID
Part ID
BAllPartsRequired
The user will select some parts (or may select none) and depending on what was selected certain questions will be displayed.
I want to join the 2 tables for 3 scenerios but do them all in 1 query. I can write each scenerio individually (EDIT I thought I could but scenario 3 I can not get to work where it requires all found in part table to be selected) but can not figure out how to get them all in 1 query (I have done something similar before but cant remember how).
If no parts exist in part table for that question retruen the question
If any part selected exists in part table return question (i.e. user selects 1 part and 5 parts are associated to that question then the question will match and be returned). BAllPartsRequired = false
If user selects parts and ALL of the parts are associated to the question the question is returend but if NOT all parts are selected by user the question is not returend (i.e. user selects 3 parts and there are 4 parts in table then the user will not see the question, but if the user selectes all 4 parts the question will be shown). BAllPartsRequired = true
I am an advanced SQL programmer but this is eluding me and I know I have done this before but how do I get it to work in 1 query, do I do a nested join, a left join, a case on the where statement or something else.
Sample Data:
Question Form Association:
NFormAssociationID NQuestionID FormType
1 1 PAEdit
2 2 PAEdit
3 3 PAEdit
4 4 PAEdit
Question Part Form Association Table:
ID NFormAssociationID PartNumber BAllPartsRequired
1 1 1 0
2 2 2 1
3 2 3 1
Query without the new parts table added:
Select ROW_NUMBER() OVER(ORDER BY QL.NOrderBy) AS RowNumber,
QL.NQuestionID, QL.FieldName, QL.Question, QL.BRequired, QFL.FormFieldType, QFL.SingleMultipleSM,
QFL.CSSStyle
FROM dbo.QuestionFormAssociation QA WITH (NOLOCK)
INNER JOIN dbo.QuestionLookup QL WITH (NOLOCK) ON QA.NQuestionID = QL.NQuestionID
INNER JOIN dbo.QuestionFieldTypeLookup QFL WITH (NOLOCK) ON QL.NFieldTypeID = QFL.NFieldTypeID
WHERE QA.BActive = 1 AND QL.BActive = 1 AND QFL.BActive=1
AND QA.FormType = 'PAEdit'
ORDER BY QL.NOrderBy
Simple query using new table
Select ID
FROM dbo.QuestionPartFormAssociation
WHERE BAllPartsRequired = 1
AND PartNumber IN ('1', '2') --'1', '2', '3')
It sounds like you are trying to find the eligible questions, based on some criteria.
In this sitatuion, it is best to summarize first at the question level, and then apply logic to those summaries. Here is an example:
select q.questionid
from (select q.questionid,
max(case when qp.questionid is null then 1 else 0 end) as HasNoParts,
sum(case when qp.partid in (<user parts>) then 1 else 0 end) as NumUserParts,
count(qp.questionid) as NumParts,
max(qp.AllPartsRequired) as AreAllPartsRequired
from question q left outer join
questionpart qp
on q.questionid = qp.questionid
group by q.questionid
) q
where HasNoParts = 1 or -- condition 1
AreAllPartsRequired = 0 and NumUserParts > 0 or -- condition 2
AreAllPartsRequired = 1 and NmUserParts = NumParts -- condition 3
I've simplified the table and column names to make the logic clearer.
updated with full answer from OP:
Select ROW_NUMBER() OVER(ORDER BY QL.NOrderBy) AS RowNumber,
QL.NQuestionID, QL.FieldName, QL.Question, QL.BRequired, QFL.FormFieldType, QFL.SingleMultipleSM,
QFL.CSSStyle
FROM dbo.QuestionFormAssociation QA WITH (NOLOCK)
INNER JOIN dbo.QuestionLookup QL WITH (NOLOCK) ON QA.NQuestionID = QL.NQuestionID
INNER JOIN dbo.QuestionFieldTypeLookup QFL WITH (NOLOCK) ON QL.NFieldTypeID = QFL.NFieldTypeID
INNER JOIN (
select q.NFormAssociationID,
max(case when qp.NFormAssociationID is null then 1 else 0 end) as HasNoParts,
sum(case when qp.PartNumber in ('1','2','3') then 1 else 0 end) as NumUserParts,
count(qp.NFormAssociationID) as NumParts,
qp.BAllPartsRequired
from QuestionFormAssociation q
left outer join QuestionPartFormAssociation qp on q.NFormAssociationID = qp.NFormAssociationID
AND QP.BActive = 1
WHERE Q.FormType = 'PAEdit'
AND Q.BActive = 1
group by q.NFormAssociationID, qp.BAllPartsRequired
) QSUB ON QA.NFormAssociationID = QSUB.NFormAssociationID
WHERE QA.BActive = 1 AND QL.BActive = 1 AND QFL.BActive=1
AND (
QSUB.HasNoParts = 1 -- condition 1
OR (QSUB.BAllPartsRequired = 0 and QSUB.NumUserParts > 0) -- condition 2
OR (QSUB.BAllPartsRequired = 1 and QSUB.NumUserParts = QSUB.NumParts) -- condition 3
)
ORDER BY QL.NOrderBy

SQL select column equivalence

I have a table that saves the possible states of other tables (entities).
But now I need to find equivalence of states between two entities.
The table structure is something like this
ID TableID StateValue StateDefinition StateDescription
================================================================
1 1 1 Created Just created
2 1 2 Dropped Just Dropped
3 2 1 Created Just Created
4 2 2 Aproved Passed the revision
5 2 3 Dropped Just dropped
I want to get equivalent (comparing text of state) which as a result get this:
TableID1 StateValue1 TableID2 StateValue2 StateDefinition
=============================================================================
1 1 2 1 Created
1 2 2 3 Dropped
My question is, how can it be done??
Do a self join on the table.
A general case might look like:
SELECT A.TableID as TableId1,
A.StateValue as StateValue1,
B.TableId as TableId2,
B.StateValue as StateValue2,
A.StateDefinition
FROM
Table A
INNER JOIN Table B
ON (A.TableId <> B.TableId and A.StateDefiniton = B.StateDefinition)
select t1.TableID as TableID1,
t1.StateValue as StateValue1,
t2.TableID as TableID2,
t2.StateValue as StateValue2,
t1.StateDefinition
from MyTable t1
inner join MyTable t2 on t1.TableID = 1 and t2.TableID = 2
where t1.StateValue = t2.StateValue
and t1.StateDefinition = t2.StateDefinition