有几种方法可以做到这一点,一种是使用 Sybase LIST 函数,如果您不介意它只在 Sybase 上运行。如果没有,那么您可以使用 RANK 和 MAX 来完成。像这样:
SELECT
CAST('2014-01-03' AS DATE) AS tape_date
,'alice' AS empl
,'K' AS val
INTO #temp_table;
INSERT INTO #temp_table VALUES('2014-01-08', 'bob', 'A');
INSERT INTO #temp_table VALUES('2014-01-01', 'bob', 'G');
INSERT INTO #temp_table VALUES('2014-01-02', 'bob', 'D');
INSERT INTO #temp_table VALUES('2014-01-05', 'bob', 'E');
-- USING SYBASE ONLY LIST FUNCTION
SELECT empl, SUBSTR(LIST(val ORDER BY tape_date), 1, 5)
FROM #temp_table
GROUP BY empl;
-- THE GENERIC WAY
SELECT
empl
,MAX(CASE rank WHEN 1 THEN val ELSE '' END)
+ ','
+ MAX(CASE rank WHEN 2 THEN val ELSE '' END)
+ ','
+ MAX(CASE rank WHEN 2 THEN val ELSE '' END)
FROM (
SELECT
RANK() OVER (PARTITION BY empl ORDER BY tape_date) AS rank
,*
FROM #temp_table) a
WHERE rank <= 3
GROUP BY
empl