[英]Multiple column match across rows
I have a database and its structure looks like this: 我有一个数据库,其结构如下所示:
Values
该表称为Values
Key, Attribute, Value
该表的列是: Key, Attribute, Value
object
is a series of rows that share the same Key
. object
是共享相同Key
的一系列行。 For example: 例如:
ROWID Key Attribute Value
***** ************************************ ********* ***********************
1 9847CAD7-C430-4401-835B-A7FCE9A33A90 FirstName Tito
2 9847CAD7-C430-4401-835B-A7FCE9A33A90 CreatedAt 2013-08-03 10:10:23:344
3 9847CAD7-C430-4401-835B-A7FCE9A33A90 UpdatedAt 2013-08-03 11:10:23:344
----- ------------------------------------ --------- -----------------------
4 4AE4B3F4-895B-4BF7-90E6-C889DA875D26 FirstName Tito
5 4AE4B3F4-895B-4BF7-90E6-C889DA875D26 CreatedAt 2013-01-01 10:10:10:344
6 4AE4B3F4-895B-4BF7-90E6-C889DA875D26 UpdatedAt 2013-01-01 10:10:10:344
In the example above I have separated the two "objects" with a series of "-" to help understand how the data is structured. 在上面的示例中,我将两个“对象”与一系列“ - ”分开,以帮助理解数据的结构。
The goal: select all rows where its UpdatedAt
value is greater than its CreatedAt
value and both share the same Key
. 目标:选择其UpdatedAt
值大于其CreatedAt
值的所有行,并且两者共享相同的Key
。 In the above example, I'd like to match Key 9847CAD7-C430-4401-835B-A7FCE9A33A90
because its UpdatedAt
value is greater than the value of CreatedAt
(the matching should occur within the same "object".) 在上述例子中,我想匹配密钥9847CAD7-C430-4401-835B-A7FCE9A33A90
因为其UpdatedAt
值比的值越大CreatedAt
(匹配应该相同的“对象”内发生。)
Any idea how I can accomplish this query? 知道如何完成这个查询吗? Thanks in advance for the help. 先谢谢您的帮助。
select
t1.key
from
Table1 t1
inner join Table1 t2 on t1.key = t2.key
where t1.Attribute = 'CreatedAt' and t2.Attribute = 'UpdatedAt'
and t1.value < t2.value
Here's my version: 这是我的版本:
SELECT Key,
MAX(CASE WHEN Attribute = 'FirstName' THEN Value END) As "First_Name",
MAX(CASE WHEN Attribute = 'CreatedAt' THEN Value END) As "Created_At",
MAX(CASE WHEN Attribute = 'UpdatedAt' THEN Value END) As "Updated_At"
FROM Value
GROUP BY Key
HAVING Created_At < Updated_At;
and SQL Fiddle 和SQL小提琴
It shows all the attributes of the matching object . 它显示匹配对象的所有属性。
Why does this feel like I am doing your homework ? 为什么这感觉就像我在做作业?
In any case it would be : 在任何情况下,它将是:
select o1.* from objects o1
join objects o2 on o1.key = o2.key
where o1.attribute = "UpdatedAt"
and o2.attribute = "CreatedAt"
and o1.value > o2.value;
Which displays : 哪个显示:
3 9847CAD7-C430-4401-835B-A7FCE9A33A90 UpdatedAt 2013-08-03 11:10:23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.