如何提取在特定字段中混合值的记录?

时间:2018-04-09 06:39:31

标签: sql sql-server tsql

我正在运行SQL Server 2012,我有一个名为StayDateInfo的下表。 该表的摘录如下:

ResaID    StayDate    RoomCat
100       2018-03-01   STD
100       2018-03-02   STD
100       2018-03-03   STD
101       2018-04-15   STD
101       2018-04-16   STD
101       2018-04-17   DLX
101       2018-04-18   DLX

此表包含大约200万行。

我需要从该表格中提取所有3列,其中RoomCatResaID对于每个StayDate都不相同。

在上面的摘录中,ResaID 101需要在输出中,因为它具有RoomCat的值(STD和DLX)的混合。

如何编写T-SQ L查询来实现此目的?

4 个答案:

答案 0 :(得分:1)

在下面的解决方案中用@xyz替换您的实际表名。

我测试的输入数据 -

declare @xyz table (ResaID    int, StayDate    date, RoomCat varchar(10))

insert into @xyz
select 100       ,'2018-03-01',   'STD' union all
select 100       ,'2018-03-02',   'STD' union all
select 100       ,'2018-03-03',   'STD' union all
select 101       ,'2018-04-15',   'STD' union all
select 101       ,'2018-04-16',   'STD' union all
select 101       ,'2018-04-17',   'DLX' union all
select 101       ,'2018-04-18',   'DLX'

解决方案 -

SELECT
    *
FROM
@xyz AS X
INNER JOIN (
    SELECT ResaID FROM @xyz GROUP BY ResaID HAVING COUNT(DISTINCT RoomCat) > 1
    ) AS Y ON Y.ResaID = X.ResaID

答案 1 :(得分:0)

加入:

SELECT
    DISTINCT ResaID, StayDate, RoomCat
FROM
    StayDateInfo
WHERE
    ResaID IN
    (
        SELECT
            first.ResaID
        FROM
            StayDateInfo first
            JOIN StayDateInfo second ON 
                first.ResaID = second.ResaID
                AND first.StayDate = second.StayDate
                AND first.RoomCat != second.RoomCat
    )

使用分组:

SELECT
  DISTINCT *
FROM
  StayDateInfo
WHERE
  ResaID IN
  (
    SELECT
      ResaID
    FROM
    (
      SELECT
          ResaID, StayDate, RoomCat
      FROM
          StayDateInfo
      GROUP BY
          ResaID, StayDate, RoomCat
    ) grouped
    GROUP BY
      ResaID, StayDate
    HAVING COUNT(1) > 1
  )

答案 2 :(得分:0)

这应该这样做:

select ResaID 
from table 
group by ResaID 
having count(distinct RoomCat) > 1

答案 3 :(得分:0)

试试这个:

 declare @tableA table(ResaID INT,StayDate DATETIME,RoomCat varchar(3))

    INSERT INTO @tableA
    SELECT 100,'2018-03-01','STD'
    union all
    SELECT 100,'2018-03-02','STD'
    union all
    SELECT 100,'2018-03-03','STD'
    union all
    SELECT 101,'2018-04-15','STD'
    union all
    SELECT 101,'2018-04-16','STD'
    union all
    SELECT 101,'2018-04-17','DLX'
    union all
    SELECT 101,'2018-04-18','DLX'


    select ResaId 
    from @tableA
    Group by ResaId
    Having COUNT(DISTINCT RoomCat)=2