简体   繁体   English

SQL聚合功能

[英]SQL aggregation functions

Given the following table 鉴于下表

Month        Product  Sales
---------    -------  -----    
January         1      10
January         2      15
February        3      23
March           1      15

The query I've used is: 我使用的查询是:

SELECT DISTINCT a.* FROM( -- possibly needed for where clause
    SELECT dateadd(month, x.MonthOffset,0) AS mes, x.produto, Sum(x.quantidade) AS vendas
    FROM
    (
        SELECT DATEDIFF(month, 0, a.data) AS MonthOffset, a.produto, a.quantidade
        FROM (
          SELECT l.*, fc.data FROM LINHAS AS l JOIN FacturaCli AS fc
              ON fc.codigo = l.codigo 
              UNION ALL
          SELECT l.*, ff.dataEmissão FROM LINHAS AS l JOIN FacturaForn AS ff
              ON ff.codigo = l.codigo
        ) AS a
    ) AS x
    GROUP BY MonthOffset, produto
) AS a

I would like to get the product with more sales per month. 我想获得每月更多销售的产品。

I'm having trouble doing query that requires a field that must not be in "aggregate group". 我在进行查询时遇到麻烦,该查询要求字段不能位于“聚合组”中。 Note that the table I provided is a result from a query. 请注意,我提供的表是查询的结果。

I'm using SQL Server 2008. I can't use temporary variables or over clause. 我正在使用SQL Server2008。不能使用临时变量或over子句。 I wouldn't like to repeat the query that lead me to this table! 我不想重复将查询引导到该表的查询! But if it is the only way, it's ok. 但是,如果这是唯一的方法,那就可以了。

Expected result: 预期结果:

Month        Product  Sales
---------    -------  -----    
January         2      15
February        3      23
March           1      15

A very tricky solution for your problem. 一个非常棘手的解决方案。

SELECT a.* 
FROM   mytable a 
       LEFT JOIN mytable b 
              ON a.Month = b.Month
                 AND a.Sales < b.Sales
WHERE  b.Month IS NULL 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM