【问题标题】:Chart sales by percent图表销售额百分比
【发布时间】:2017-10-01 07:35:51
【问题描述】:

我想制作一个图表,获取产品的数量和产品的销售额,并在可能的情况下在图表中显示销售额的百分比。

例如ProductA 数量:100,ProductA 销售:50。所以它的销售额为 50%。

我现在有这个工作图表,它汇总了产品的所有销售额,但它没有显示数量。 (数量来自另一个名为 Products 的表)

如果我让这些工作,例如,我想在图表中显示销售额仅高于 50% 的产品或销售额仅低于 50% 的产品。

private void loadchartFastt()
{
    chart1.Series[0].Points.Clear();
    chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
    using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString))
    {
        if (cnn.State == ConnectionState.Closed)
            cnn.Open();
        SqlCommand command = new SqlCommand("SELECT TOP 5 ProductName, Sum(QtySold) as QtySold FROM Sales_productholder group by ProductName order by SUM(QtySold) desc", cnn); //top selling with desc

        SqlDataReader read = command.ExecuteReader();

        while (read.Read())
        {
            this.chart1.Series["Pieces Sold"].Points.AddXY(read["ProductName"], read["QtySold"]);

        }
        read.Close();

    }
}

根据 Jeric 先生的回答更新图片。

【问题讨论】:

  • Sales_productholderProducts 有关系吗?
  • 是的,先生,它们与 ProductID 相关
  • 使用 JOIN 按 ProductID 组合 Products 表和 ProductName 表。

标签: c# sql winforms charts


【解决方案1】:

为了实现这一点,你可以试试这个:

  1. 根据'ProductID'的关系加入两个表
  2. 执行一个表达式列,通过[Total Sold Quantity]/[Quantity] * 100 获得销售百分比。

注意:我们必须将 sp.QtySoldQuantity 转换为浮点数才能 得到带小数点的结果。然后你可以把表达式括起来 DECIMAL 只显示两位小数。

  1. 然后添加另一个系列以显示销售百分比。

以下是我根据您的场景所做的示例查询:

试试下面的代码:

var sql = @"SELECT TOP 5 
                sp.ProductName, 
                SUM(sp.QtySold) AS QtySold,
                p.Quantity,
                CAST((CAST(SUM(sp.QtySold) AS FLOAT) / CAST(p.Quantity AS FLOAT)) * 100 AS DECIMAL(8,2)) [SalesPercentage]
            FROM 
                Sales_productholder sp
                JOIN Products p ON (sp.ProductID = p.ProductID)
            GROUP BY 
                sp.ProductName, p.ProductID, p.Quantity
            ORDER BY 
                SUM(sp.QtySold) DESC";
SqlCommand command = new SqlCommand(sql, cnn); //top selling with desc
SqlDataReader read = command.ExecuteReader();
while (read.Read())
{
    this.chart1.Series["Pieces Sold"].Points.AddXY(read["ProductName"], read["QtySold"]);
    //add another series for the sold %
    this.chart1.Series["Sold Percentage"].Points.AddXY(read["ProductName"], read["SalesPercentage"]);
}

结果:

您可以尝试下载此源代码以供参考: https://github.com/makubex88/SampleChartWinform

【讨论】:

  • 谢谢 jerc 先生!但我认为图表看起来不太正确。我将在问题中包含图表的图片。谢谢
  • 我刚刚意识到我的问题和我想要发生的事情很难,因为随着销量的增加,数量正在减少。
  • 只需检查chart1 中的正确变量,百分比的最大值为 100%,因此图表中为 100
  • 我设法做到了,先生。你能告诉我如何在查询中添加 where 条件吗?条件是。 ... 和 [SalesPercentage] >50 之间的日期
  • 您可以将HAVING 用于具有聚合函数的条件,将WHERE 用于日期
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
相关资源
最近更新 更多