Where子句与计算列

时间:2017-10-01 16:53:12

标签: sql

你好我想在这里添加一个条件,如where Date between ..SalesPercentage > 50,但它的salespercentage不是db中的一个列,它只是像下面的代码一样输入。

我该如何使用它。提前谢谢。

      var sql = @"SELECT TOP 10 
                    sp.ProductName, 
                    SUM(sp.QtySold) AS QtySold,
                    SUM(r.QtyinPieces) AS StockLimit,                  
                    CAST(    (CAST    (SUM(sp.QtySold) AS FLOAT)     /    CAST(SUM(r.QtyinPieces) AS FLOAT)  ) * 100 AS DECIMAL(8,2)       ) [SalesPercentage]
                FROM 
                    Sales_productholder sp
                    JOIN Orders_productholder r ON (sp.ProductID = r.ProductID)

                GROUP BY 
                    sp.ProductName, r.ProductID, r.QtyinPieces
                ORDER BY 
                    SUM(sp.QtySold) DESC";

更新:我的组合框有5,10,20这样的项目,我想将它用作Top 5的参数。但它总是导致错误Incorrect syntax near TOP

这是我试过的:

SELECT TOP @Top

command.Parameters.AddWithValue("@Top", cboTop.SelectedItem.ToString());

string topp = cboTop.SelectedItem.ToString();
 command.Parameters.AddWithValue("@Top", topp);

1 个答案:

答案 0 :(得分:0)

您可以像这样添加HAVING

HAVING
    CAST( (CAST ( SUM(sp.QtySold) AS FLOAT) / CAST(SUM(r.QtyinPieces) AS FLOAT) ) * 100 AS DECIMAL(8,2) ) > 50

所有查询:

SELECT TOP 10 
    sp.ProductName, 
    SUM(sp.QtySold) AS QtySold,
    SUM(r.QtyinPieces) AS StockLimit,                  
    CAST( (CAST ( SUM(sp.QtySold) AS FLOAT) / CAST(SUM(r.QtyinPieces) AS FLOAT) ) * 100 AS DECIMAL(8,2) ) [SalesPercentage]
FROM 
    Sales_productholder sp
    JOIN Orders_productholder r ON (sp.ProductID = r.ProductID)
WHERE [Date] between @DateBegin and @DateAdd
GROUP BY 
    sp.ProductName, r.ProductID, r.QtyinPieces
HAVING
    CAST( (CAST ( SUM(sp.QtySold) AS FLOAT) / CAST(SUM(r.QtyinPieces) AS FLOAT) ) * 100 AS DECIMAL(8,2) ) > 50
ORDER BY 
    SUM(sp.QtySold) DESC