Sql server SQL查询以获取具有最大日期的商户名称
我想实现以下目标,但不确定如何进行。任何指向正确方向的查询都会有很大帮助 桌子:我下面有三张桌子#Sql server SQL查询以获取具有最大日期的商户名称,sql-server,tsql,Sql Server,Tsql,我想实现以下目标,但不确定如何进行。任何指向正确方向的查询都会有很大帮助 桌子:我下面有三张桌子# 如何返回类别名称,商户数量,商户名称,以及最长日期,我希望看到您的努力 所以我现在违背了这些原则 试试这个: select c.Name as category_name, count(*) as Merchant_Count, m.Name as Merchant_Name, max(Date) from Merchant m join MerchantCategory mc on m.Me
如何返回
类别名称
,商户数量
,商户名称
,以及最长日期
,我希望看到您的努力
所以我现在违背了这些原则
试试这个:
select c.Name as category_name, count(*) as Merchant_Count, m.Name as Merchant_Name, max(Date) from
Merchant m join MerchantCategory mc
on m.MerchantId = mc.MerchantId
join Category c
on mc.CategoryId = c.CategoryId
group by c.Name, m.Name
根据该要求,我了解到每个类别应有一行,应显示商户数量,并应显示商户名称和最新日期 我在下面准备了一个查询,它生成了一些示例数据,并提供了我理解的预期结果 其工作方式是通过将商户类别表连接到类别表,然后计算每个类别的商户id来计算商户交易量。该名称更为复杂,需要使用外部应用程序,即按类别(每行)计算最大(日期)描述排序的商户表中的前1个名称 我希望这有帮助,任何问题请让我知道
declare @Merchant table (
MerchantId int,
Name nvarchar(25),
Date Date
);
declare @MerchantCategory table (
MerchantId int,
CategoryId int
);
declare @Category table (
CategoryId int,
Name nvarchar(25)
);
insert into @Merchant (MerchantId, Name, Date)
values
(1, 'Lucy', '2019-01-05'),
(2, 'Dave', '2019-01-30'),
(3, 'Daniel' ,'2019-02-01');
insert into @MerchantCategory (MerchantId, CategoryId)
values
(1, 4),
(1, 5),
(2, 4),
(3, 5);
insert into @Category (CategoryId, Name)
values
(4, 'Cat1'),
(5, 'Cat2');
select c. Name, max(m.name) as MaxMerchantName, count(distinct mc2.merchantid) as Merchantvol from @Category c
left join @MerchantCategory mc2 on c.CategoryId=mc2.CategoryId
outer apply (select top 1 name, max(date) as date from @Merchant m inner join @MerchantCategory mc on m.MerchantId=mc.MerchantId where c.CategoryId=mc.CategoryId group by Name order by max(date) desc) m
group by c.Name;
如果您使用数据和预期输出更新您的问题,那将非常好。这会带来正确的结果,只是想知道查询是否需要如此复杂?谢谢你的努力。嗨,新浪,大部分查询都是生成样本数据。获取max date的名称有点棘手,因为categoryid和merchantid之间有1:1的映射。如果答案已经解决了你的问题,请你将其标记为已接受它不允许我投票抱歉,我的可信度很低,不知道如何感谢你哦,伟大的上帝,每个答案旁边都应该有一个复选框,允许你将其标记为已接受。那就太感谢了。
declare @Merchant table (
MerchantId int,
Name nvarchar(25),
Date Date
);
declare @MerchantCategory table (
MerchantId int,
CategoryId int
);
declare @Category table (
CategoryId int,
Name nvarchar(25)
);
insert into @Merchant (MerchantId, Name, Date)
values
(1, 'Lucy', '2019-01-05'),
(2, 'Dave', '2019-01-30'),
(3, 'Daniel' ,'2019-02-01');
insert into @MerchantCategory (MerchantId, CategoryId)
values
(1, 4),
(1, 5),
(2, 4),
(3, 5);
insert into @Category (CategoryId, Name)
values
(4, 'Cat1'),
(5, 'Cat2');
select c. Name, max(m.name) as MaxMerchantName, count(distinct mc2.merchantid) as Merchantvol from @Category c
left join @MerchantCategory mc2 on c.CategoryId=mc2.CategoryId
outer apply (select top 1 name, max(date) as date from @Merchant m inner join @MerchantCategory mc on m.MerchantId=mc.MerchantId where c.CategoryId=mc.CategoryId group by Name order by max(date) desc) m
group by c.Name;