SQL获取最新记录

时间:2017-04-06 09:49:13

标签: sql date row combinations

我在这里努力从这张表中取出两个结果。我有一个表格,其中包含不同日期的不同类型,项目和值。

Type Item Value Date
1    10   111   20160101
1    10   122   20170101
1    11   222   20170101
1    12   312   20170101
2    10   144   20160101
2    10   155   20170101
2    11   105   20160101
2    11   133   20170101
2    11   123   20180101
3    10   111   20170101

首先,我想要最新的日期,在类型,项目的组合上显示。我试过了这个查询,但它会告诉我所有日期。

SELECT Type, Item, Value, MAX(Date) as Date from TABLENAME
WHERE Type='1' or Type='2'
GROUP BY Type, Item, Value

以下是我希望它的样子。

Type Item Value Date
1    10   122   20170101
1    11   222   20170101
1    12   312   20170101
2    10   155   20170101
2    11   123   20180101

然后我们有了更棘手的问题,在这里我完全迷失了,不确定是否可能,或者我应该以其他方式做到这一点?我想看看类型1的项是否有值,而类型2没有。或者相反。显示在新表中。

Item Type1 Type2 Date
10   1     2     20170101 -> Item 10 has values with both type 1,2 on specific date
11   1           20170101 -> Item 11 has only a value when type 1 on specific date
11         2     20180101 -> Item 11 has only a value when type 2 on specific date
12   1           20170101 -> Item 12 has only a value when type 1 on specific date

2 个答案:

答案 0 :(得分:3)

对于您认为可以使用的第一个问题:

SELECT A.TYPE, A.ITEM, A.VALUE, A.DATE 
FROM TABLENAME A
INNER JOIN ON (SELECT TYPE, ITEM, MAX(DATE) AS MAXDATE
                FROM TABLENAME
                GROUP BY TYPE, ITEM) B ON A.TYPE = B.TYPE AND A.ITEM = B.ITEM AND A.DATE=B.MAXDATE
WHERE A.TYPE='1' OR A.TYPE='2'

第二,你可以试试这个:

SELECT DISTINCT A.ITEM, B.TYPE AS TYPE1, C.TYPE AS TYPE2, CASE WHEN B.TYPE IS NOT NULL THEN B.DAT ELSE C.DAT END AS DATE_X 
FROM 
    (SELECT ITEM, TYPE, MAX(DATE) AS DAT
     FROM ITEM
     GROUP BY ITEM, TYPE) A
     LEFT JOIN (SELECT ITEM, TYPE, MAX(DATE) AS DAT FROM ITEM WHERE TYPE='1' GROUP BY ITEM, TYPE) B ON A.ITEM = B.ITEM AND A.DAT= B.DAT
     LEFT JOIN (SELECT ITEM, TYPE, MAX(DATE) AS DAT FROM ITEM WHERE TYPE='2' GROUP BY ITEM, TYPE) C ON A.ITEM = C.ITEM AND A.DAT= C.DAT

输出:

    ITEM    TYPE1   TYPE2   DATE_X
1   10  1   2   20170101
2   11  NULL    2   20180101
3   11  1   NULL    20170101
4   12  1   NULL    20170101

答案 1 :(得分:-1)

对于您的第一个场景,您可以使用以下查询

SELECT Type, Item, Value, Date from TABLENAME
WHERE (Type='1' or Type='2') and date = (SELECT MAX(Date) from TABLENAME)