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.
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