前前浪 2020-05-27 16:08 采纳率: 33.3%
浏览 319
已采纳

sql 语句:对某字段排序后,求占总数60%的前x条数据

如图:求前n条数据,这n条数据的产量之和,占总产量的60%
(注意要按产品排序后的前n条数据)

图片说明

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-05-27 16:40
    关注

    太复杂了,拿LINQ写了一个,看帮你转换的SQL

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Q1078172
    {
        class Program
        {
            static void Main(string[] args)
            {
                DataClasses1DataContext db = new DataClasses1DataContext();
                db.Log = Console.Out;
                var query =
                    (from x in db.Table1s.OrderByDescending(x => x.qnt)
                    let acc = x.qnt + (db.Table1s.Any(y => x.qnt <= y.qnt && x.name != y.name) ? db.Table1s.Where(y => x.qnt <= y.qnt && x.name != y.name).Select(y => y.qnt).Sum() : 0)
                     where acc < db.Table1s.Select(y => y.qnt).Sum() * 60 / 100
                     select new { acc, x }).OrderBy(x => x.acc);
    
                foreach (var item in query)
                    Console.WriteLine(item.x.name + "," + item.x.qnt + ",      " + item.acc);
            }
        }
    }
    
    
    hung,100,      100
    thai,80,      260
    cn,80,      260
    

    对应的sql (表名叫Table1,国家id叫id,国家名称叫name,产量叫qnt)

    SELECT [t3].[value] AS [acc], [t3].[id], [t3].[name], [t3].[qnt]
    FROM (
        SELECT [t0].[id], [t0].[name], [t0].[qnt], [t0].[qnt] + (
            (CASE
                WHEN EXISTS(
                    SELECT NULL AS [EMPTY]
                    FROM [dbo].[Table1] AS [t1]
                    WHERE ([t0].[qnt] <= [t1].[qnt]) AND ([t0].[name] <> [t1].[name]
    )
                    ) THEN (
                    SELECT SUM([t2].[qnt])
                    FROM [dbo].[Table1] AS [t2]
                    WHERE ([t0].[qnt] <= [t2].[qnt]) AND ([t0].[name] <> [t2].[name]
    )
                    )
                ELSE 0
             END)) AS [value]
        FROM [dbo].[Table1] AS [t0]
        ) AS [t3]
    WHERE [t3].[value] < (SELECT SUM([t0].[qnt]) * 60 / 100
    FROM [dbo].[Table1] AS [t0])
    ORDER BY [t3].[value], [t3].[qnt] DESC
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库