我更新了下面的问题,因为它的复杂性更高...
有关基于类型的SQL分组的问题吗?
我希望能够列出A型的最大值(基于日期-每个CustID),同时列出B型的所有值
从这里开始:
Date Ref Type CustID
2019-03-04 123 A 1
2019-03-05 124 A 1
2019-03-06 125 B 3
2019-03-07 126 B 4
2019-03-08 127 B 5
2019-03-06 128 A 2
2019-03-07 129 A 2
2019-03-08 130 A 2
对此:
Date Ref Type CustID
2019-03-05 124 A 1
2019-03-06 125 B 3
2019-03-07 126 B 4
2019-03-08 127 B 5
2019-03-08 130 A 2
预先感谢:-)
答案 0 :(得分:1)
这是您想要的吗?
with a as (
select top (1) t.*
from t
where type = 'A'
order by ref desc
)
select a.*
from a
union all
select t.*
from t
where type = 'B';
或者没有union all
:
select top (1) with ties t.*
from t
order by (case when type = 'B' then 1
else row_number() over (partition by type order by ref desc
end);
答案 1 :(得分:0)
全部使用联盟
select date,ref,type from table where type='B'
union all
select date,ref,type from table where type='A'
and date = (select max(date) from table where type='A')
答案 2 :(得分:0)
尝试使用union all
select top 1 date,ref, type from tablename
where Type='A' order by date desc
union all
select date,ref, type from tablename
where type='B'
答案 3 :(得分:0)
以下查询为您提供了类型为A
的记录,其中包含最新日期和B
记录
Select * from
( SELECT Date, Ref, Type
FROM TABLE
WHERE TYPE='A' GROUP BY TYPE
HAVING DATE =MAX(DATE)
UNION
SELECT Date, Ref, Type FROM TABLE
WHERE TYPE='B'
)