我有一个数据库,其结构如下所示:
Values
Key, Attribute, Value
object
是一系列共享相同Key
。例如:
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
在上面的示例中,我将两个“对象”与一系列“ - ”分开,以帮助理解数据的结构。
目标:选择其UpdatedAt
值大于其CreatedAt
值的所有行,并且两者共享相同的Key
。在上面的示例中,我想匹配键9847CAD7-C430-4401-835B-A7FCE9A33A90
,因为它的UpdatedAt
值大于CreatedAt
的值(匹配应该出现在同一个“对象”中。)< / p>
知道如何完成此查询吗?在此先感谢您的帮助。
答案 0 :(得分:1)
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
答案 1 :(得分:1)
这是我的版本:
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;
它显示匹配的对象的所有属性。
答案 2 :(得分:0)
为什么这就像我在做作业一样?
无论如何,它将是:
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;
显示:
3 9847CAD7-C430-4401-835B-A7FCE9A33A90 UpdatedAt 2013-08-03 11:10:23