如果过去曾经问过这个问题,请接受我的道歉,但是我已经完成了问题并找不到答案。
我有一个包含多个条目的表格如下:
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'
答案 0 :(得分: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`
答案 1 :(得分: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”行的情况,但它确实依赖于任何值只存在单个“S”行和单个“E”行“关键”。
答案 2 :(得分:0)
您只需要这个SQL语句:
SELECT key, code, MIN(Date) AS S_Date, MAX(Date) AS E_Date
FROM Table1
GROUP BY key, code
如果你总是有一对行,那么一行的类型=&#39; S&#39;和另一个类型=&#39; E&#39; 然后改进版本是:
SELECT key, code, MIN(Date) AS S_Date, MAX(Date) AS E_Date
FROM Table1
GROUP BY key, code
HAVING count(*) = 2