子查询foxpro

时间:2015-11-14 18:30:44

标签: sql subquery visual-foxpro

SELECT category, SUM(price*amount);
 FROM dan2.dbf WHERE;
  between(date_p, {^2014-01-01}, {^2014-12-31});
    GROUP BY category

enter image description here

此查询查找日期类别和某些条件的总和。我需要找到总和的最大值(由subkuery)。

2 个答案:

答案 0 :(得分:2)

详细信息取决于您使用的VFP版本 - 在最新的VFP 9中,您可以执行类似

的操作
* create test data
CREATE CURSOR test (id Int, category Int, price Num(15,2), amount Int, dateP D)
INSERT INTO test VALUES (1, 2, 24.25, 15, {^2014-10-5})
INSERT INTO test VALUES (2, 2, 700.0, 15, {^2014-7-25})
INSERT INTO test VALUES (3, 2, 110.10, 210, {^2015-11-15})
INSERT INTO test VALUES (4, 3, 110.10, 11, {^2014-11-15})

* your original 
SELECT category, SUM(price*amount) ;
    FROM test ;
    WHERE datep Between {^2014-01-01} And {^2014-12-31} ;
    GROUP BY category

* your desired result w/o sub-query
SELECT SUM(price*amount) ;
    FROM test ;
    WHERE datep Between {^2014-01-01} And {^2014-12-31} 

* the desired sub-query you described
SELECT SUM(Total) ;
    FROM ( ;
        SELECT category, SUM(price*amount) As Total ;
            FROM test ;
            WHERE datep Between {^2014-01-01} And {^2014-12-31} ;
            GROUP BY category ;
            ) As subQuery

编辑:

* as per your comment
SELECT TOP 1 category, Max(Total) ;
    FROM ( ;
        SELECT category, SUM(price*amount) As Total ;
            FROM test ;
            WHERE datep Between {^2014-01-01} And {^2014-12-31} ;
            GROUP BY category ;
            ) As subQuery ;
    GROUP BY 1 ;
    ORDER BY 2 Desc

答案 1 :(得分:1)

  

我需要找到最大值

您可以通过单个查询轻松获取最大值和在查询上使用ORDER DESC然后获取TOP值。

SELECT category,  
SUM(price*amount) AS Sum_Val;  
FROM dan2.dbf WHERE;  
between(date_p, {^2014-01-01}, {^2014-12-31});  
GROUP BY category  
ORDER BY 2 DESC  
INTO CURSOR TmpResults  

SELECT TmpResults  
GO TOP  
MaxSum = TmpResults.Sum_Val  

祝你好运