22,210
社区成员
发帖
与我相关
我的任务
分享
现在有字段
ID 车牌号 消费门店编号,消费门店名称,消费时间
id,che_no,GongSiNo,GongSiMc,xche_jsrq
1 津A12345 01 天津1店 2018-06-07 16:16
2 津A12345 01 天津1店 2018-06-10 16:16
3 津A45678 06 天津6店 2018-05-06 16:16
4 津A12345 06 天津6店 2018-05-02 16:16
5 津A12345 01 天津1店 2018-04-04 16:16
现在想到的SQL语句,只能查询出来去过其他店的车牌,但是实现不了需求
with t as (
select che_no,GongSiMc from work_pz_sj
where
-- che_no='黑E67H17'
xche_jsrq>'2016-01-01 00:00' and xche_jsrq<'2018-06-07 23:59'
and GongSiNo in('02','08')
group by che_no,GongSiMc having count(che_no) >=2
)
select che_no,MIN(GongSiMc) from t group by che_no having count(che_no) >=2
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[che_no] nvarchar(27),[GongSiNo] nvarchar(22),[GongSiMc] nvarchar(24),[xche_jsrq] DATETIME)
Insert #T
select 1,N'津A12345',N'01',N'天津1店','2018-06-07 16:16' union all
select 2,N'津A12345',N'01',N'天津1店','2018-06-10 16:16' union all
select 3,N'津A45678',N'06',N'天津6店','2018-05-06 16:16' union all
select 4,N'津A12345',N'06',N'天津6店','2018-05-02 16:16' union all
select 5,N'津A12345',N'01',N'天津1店','2018-04-04 16:16'
Go
--测试数据结束
;WITH CTE AS (
SELECT che_no,
GongSiNo,
[GongSiMc],
xche_jsrq,
ROW_NUMBER() OVER (PARTITION BY che_no ORDER BY xche_jsrq) rn
FROM #T
)
SELECT CTE.GongSiNo,
[GongSiMc],
(
SELECT COUNT(1)
FROM #T
WHERE che_no = CTE.che_no
AND xche_jsrq > CTE.xche_jsrq
AND GongSiNo <> CTE.GongSiNo
) AS 合计
FROM CTE
WHERE rn = 1;
with cte
as
(select *,ROW_NUMBER() over (partition by che_no order by xche_jsrq) as seq from 消费明细表)
select GongSiNo,GongSiMc,COUNT(1) as total from cte A
where exists (select 1 from cte where A.che_no=che_no and seq=1 and A.GongSiNo<>GongSiNo)
group by GongSiNo,GongSiMc