0

如果过去有人问过这个问题,请接受我的歉意,但我已经回答了这些问题,但找不到答案。

我有一个包含多个条目的表,如下所示:

    key   | type   | Code  | Date

    1234  | S      | 10DY  | 01/10/2012
    1234  | E      | 10DY  | 31/10/2012
    12376 | S      | 10DY  | 11/10/2012
    12376 | E      | 10DY  | 21/10/2012

我想提取数据,使其如下所示:

    key   |  Code  | S_Date     | E_Date

    1234  |  10DY  | 01/10/2012 | 31/10/2012
    12376 |  10DY  | 11/10/2012 | 21/10/2012

目前我有这个:

SELECT  key, code, CASE WHEN type = 'S' THEN Date END AS S_Date, 
CASE WHEN type = 'E' THEN Date END AS E_Date
FROM  Table1
WHERE code = '10DY'
4

3 回答 3

0

仅基于列的名称并在表上没有任何规定的约束的情况下做出一些直觉上的飞跃,以下应该可以满足您的需要:

SELECT s1.key, s1.code, s1.date AS S_date, s2.date AS E_date
FROM startend s1 LEFT JOIN startend s2 ON s1.key = s2.key AND s1.type <> s2.type
WHERE s1.date < s2.date OR s2.date IS NULL;

此查询处理存在“S”行但还没有“E”行的情况,但它确实依赖于对于任何“key”值只有一个“S”行和一个“E”行”。

于 2013-11-06T11:21:18.343 回答
0

您只需要这条 SQL 语句:

SELECT key, code, MIN(Date) AS S_Date, MAX(Date) AS E_Date 
FROM Table1
GROUP BY key, code

如果您总是有一对行,一个具有 type = 'S' 而另一个具有 type = 'E' 那么改进的版本是:

SELECT key, code, MIN(Date) AS S_Date, MAX(Date) AS E_Date 
FROM Table1
GROUP BY key, code
HAVING count(*) = 2
于 2014-08-04T12:50:55.520 回答
0

假设 S_Date < E_Date,应该这样做:

SELECT `key`, `code`, MIN(`Date`) AS S_Date, MAX(`Date`) AS E_Date FROM Table1 WHERE code='10DY' GROUP BY `key`
于 2013-11-04T16:41:45.840 回答