T-SQL查询根据一个特定列

时间:2015-06-25 10:20:18

标签: sql-server group-by duplicates having

我正在运行SQL Server 2014,并且我有以下T-SQL查询:

 USE MYDATABASE

 SELECT * 
 FROM RESERVATIONLIST
 WHERE [MTH] IN ('JANUARY 2015','FEBRUARY 2015')
上面代码中提到的

RESERVATIONLIST是一个视图。该查询给出了以下输出(提取):

ID     NAME       DOA         DOD       Nights Spent       MTH
--------------------------------------------------------------------
251    AH     2015-01-12   2015-01-15      3           JANUARY 2015
258    JV     2015-01-28   2015-02-03      4           JANUARY 2015
258    JV     2015-01-28   2015-02-03      2           FEBRUARY 2015

上述输出包含大约12,000条记录。

我需要修改我的查询,以便它消除所有重复的ID并给我以下结果:

 ID    NAME       DOA          DOD       Nights Spent       MTH
 --------------------------------------------------------------------
 251     AH     2015-01-12   2015-01-15      3           JANUARY 2015
 258     JV     2015-01-28   2015-02-03      4           JANUARY 2015

我尝试过类似的东西,但它不起作用:

USE MYDATABASE

SELECT * 
FROM RESERVATIONLIST
WHERE [MTH] IN ('JANUARY 2015', 'FEBRUARY 2015')    
GROUP BY [ID] 
HAVING COUNT ([MTH]) > 1

2 个答案:

答案 0 :(得分:3)

以下查询将为每个ID返回一行:

SELECT * FROM 
(
    SELECT *,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY (SELECT NULL)) rn FROM RESERVATIONLIST
    WHERE [MTH] IN ('JANUARY 2015','FEBRUARY 2015')
) T
WHERE rn = 1

注意:这将从具有相同ID的多个行返回一个随机行。如果要选择某个特定行,则必须在order by中定义它。对于例如:

SELECT * FROM 
(
    SELECT *,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DOA DESC) rn FROM RESERVATIONLIST
    WHERE [MTH] IN ('JANUARY 2015','FEBRUARY 2015')
) T
WHERE rn = 1

肯定会返回max(DOA)行。

答案 1 :(得分:1)

你正在尝试做一个GROUP BY语句,恕我直言是正确的方法。您应该制定所有常量列,并汇总其他列。根据DOD和DOA的值,我可以看到两种解决方案:

SELECT ID,NAME,DOA,DOD,SUM([Nights Spent]) as Nights,
   min(MTH) as firstRes, max(MTH) as lastRes
FROM RESERVATIONLIST
GROUP BY ID,NAME,DOA,DOD

OR

SELECT ID,NAME,min(DOA) as firstDOA,max(DOD) as lastDOD,SUM([Nights Spent]) as Nights,
   min(MTH) as firstRes, max(MTH) as lastRes
FROM RESERVATIONLIST
GROUP BY ID,NAME