需要使用distinct,count,max的数据列表

zf2sa74q  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(364)

表格结构如下:,

我的第一个sql查询如下所示,

  1. SELECT DISTINCT(IndustryVertical)
  2. , COUNT(IndustryVertical) AS IndustryVerticalCount
  3. , City
  4. FROM `records`
  5. WHERE City!=''
  6. GROUP
  7. BY IndustryVertical
  8. , City
  9. ORDER
  10. BY `IndustryVerticalCount` DESC

通过运行上面的查询,我得到下面的结果,

我要做的是得到所有不同城市的列表,只有一个max(industryverticalcount)和industryvertical。
尝试了几件没有希望的事。
任何人,请引导我。
每个城市都有好几条记录。我想要达到的是,
所有不同的城市价值观
最大工业垂直计数
行业名称垂直
我得到的记录如下,

我想要得到的,

以上记录仅供参考。在这里,您只能看到不同的城市值,其中只有一个垂直名称具有最大计数。

gupuwyp2

gupuwyp21#

我想你只是想要一个 HAVING 条款:

  1. SELECT r.IndustryVertical,
  2. COUNT(*) AS IndustryVerticalCount,
  3. r.City
  4. FROM records r
  5. WHERE r.City <> ''
  6. GROUP BY r.IndustryVertical, r.City
  7. HAVING COUNT(*) = (SELECT COUNT(*)
  8. FROM records r2
  9. WHERE r2.City = r.City
  10. ORDER BY COUNT(*) DESC
  11. LIMIT 1
  12. )
  13. ORDER BY IndustryVerticalCount DESC;
zvokhttg

zvokhttg2#

这个怎么样?我认为应该这样做:

  1. DECLARE @DataSet TABLE (
  2. City VARCHAR(50),
  3. IndustryVertical VARCHAR(50),
  4. IndustryVerticalCount INT
  5. )
  6. INSERT INTO @DataSet SELECT 'Bangalore', 'Consumer Internet', 279
  7. INSERT INTO @DataSet SELECT 'Bangalore', 'Technology', 269
  8. INSERT INTO @DataSet SELECT 'Bangalore', 'Logistics', 179
  9. INSERT INTO @DataSet SELECT 'Mumbai', 'Technology', 194
  10. INSERT INTO @DataSet SELECT 'Mumbai', 'Consumer Internet', 89
  11. SELECT
  12. table_a.*
  13. FROM @DataSet table_a
  14. LEFT JOIN @DataSet table_b
  15. ON table_a.City = table_b.City
  16. AND table_a.IndustryVerticalCount < table_b.IndustryVerticalCount
  17. WHERE table_b.IndustryVerticalCount IS NULL
展开查看全部
q5lcpyga

q5lcpyga3#

由于您使用的是group by,它将只自动选择不同的行。因为您在两列上使用GROUPBY,所以您将得到只有两列的组合是不同的行。
您现在要做的是使用这个结果表,并对其执行查询以查找按城市分组的最大计数。

  1. SELECT IndustryVertical, IndustryVerticalCount, City from
  2. ( SELECT IndustryVertical
  3. , COUNT(IndustryVertical) AS IndustryVerticalCount
  4. , City
  5. FROM `records`
  6. WHERE City!=''
  7. GROUP
  8. BY IndustryVertical
  9. , City) as tbl where IndustryVerticalCount IN (Select max(IndustryVerticalCount) from ( SELECT IndustryVertical
  10. , COUNT(IndustryVertical) AS IndustryVerticalCount
  11. , City
  12. FROM `records`
  13. WHERE City!=''
  14. GROUP
  15. BY IndustryVertical
  16. , City) as tbl2 where tbl.City=tbl2.city)

这也许不是最有效的方法,但我认为它会奏效。

展开查看全部

相关问题