patternsqlModerate
Where clause over multiple rows, GROUP BY
Viewed 0 times
rowsgroupwhereovermultipleclause
Problem
I have the following table structure
I want to be able to Select all rows where Property == Status and Value == Active And Property == RegistrationDate and Value == 2018-05-11 11:30:14.000
Im figuring I need to do some kind of GROUP BY and then select on that aggregation but I can't get my head around it(my sql is really rusty).
I want the following output for the above "query"
If all the columns had existed on the same row I would just write something like this:
AccountID Property Value
123456 Status Active
123456 City Los Angeles
123456 RegistrationDate 2018-05-11 11:30:14.000
543210 Status Active
543210 City Las Vegas
543210 RegistrationDate 2018-05-11 11:13:14.000
888888 Status Inactive
888888 City Toronto
888888 RegistrationDate 2015-05-12 11:13:14.000I want to be able to Select all rows where Property == Status and Value == Active And Property == RegistrationDate and Value == 2018-05-11 11:30:14.000
Im figuring I need to do some kind of GROUP BY and then select on that aggregation but I can't get my head around it(my sql is really rusty).
I want the following output for the above "query"
AccountID Status RegistrationDate
123456 Active 2018-05-11 11:30:14.000
543210 Active 2018-05-11 11:30:14.000If all the columns had existed on the same row I would just write something like this:
SELECT AccountID FROM Property
WHERE Status = 'Active'
AND RegistrationDate = '2018-05-11 11:30:14.000'Solution
The design pattern is called EAV (entity-attribute-value). It's usual to need either
GROUP BY or queries with multiple joins with this design:SELECT
a.AccountID
FROM
tbl AS a
JOIN tbl AS b
ON a.AccountID = b.AccountID
WHERE
a.Property = 'Status'
AND a.Value = 'Active'
AND b.Property = 'RegistrationDate'
AND b.Value = '2018-05-11 11:30:14.000' ;Code Snippets
SELECT
a.AccountID
FROM
tbl AS a
JOIN tbl AS b
ON a.AccountID = b.AccountID
WHERE
a.Property = 'Status'
AND a.Value = 'Active'
AND b.Property = 'RegistrationDate'
AND b.Value = '2018-05-11 11:30:14.000' ;Context
StackExchange Database Administrators Q#209989, answer score: 10
Revisions (0)
No revisions yet.