1
In my example, I have a query that return 3 products and the same were purchased in different orders but I do not need this order number. So I did it this way:
SELECT
c.prod_pk_id,
'61068276007702' as CNPJ,
'teste' AS FABRICANTE,
c.prod_pk_id AS CODIGOPRODUTO,
c.prod_nome AS NOMEPRODUTO,
case
when CAST(CAST(c.PROD_COD_BARRAS AS BIGINT) AS VARCHAR) = '0' then C.PROD_CODIGO_EXTERNO
when CAST(CAST(c.PROD_COD_BARRAS AS BIGINT) AS VARCHAR) <> '' then CAST(CAST(c.PROD_COD_BARRAS AS BIGINT) AS VARCHAR) end as CODIGOBARRAS,
(b.pedip_qtde * 1000) AS QTDVENDIDO, 'BRL' as MOEDA,
CAST(a.pedi_dt_compra AS DATE) as DATA_VENDA,
b.PEDIP_VALOR_POR as TOTAL_PRODUTO,
( cast( b.PEDIP_VALOR_POR * b.pedip_qtde as Int) * 1000) AS TOTAL_PEDIDO,
( select sum(PRODP_QTDE_ESTOQUE * 1000) from TB_PRODUTO_PRECO where PRODP_FK_PROD_ID = c.prod_pk_id ) as ESTOQUETOTAL
FROM TB_PEDIDO A
INNER JOIN TB_CLIENTE G ON G.CLIE_PK_ID = A.PEDI_FK_CLIE_ID
inner join TB_PEDIDO_PRODUTO b on a.PEDI_PK_ID = b.PEDIP_FK_PEDI_ID
inner join TB_PRODUTO C on c.prod_pk_id = b.PEDIP_FK_PROD
inner join TB_FABRICANTE d on d.FABR_PK_ID = c.PROD_FK_FABR_ID
where d.fabr_nome like '%teste%'
and A.pedi_dt_compra between '2017-01-02' and '2017-01-03'
and c.prod_pk_id = 62168
group by c.prod_pk_id,
c.prod_nome,c.PROD_COD_BARRAS,C.PROD_CODIGO_EXTERNO,b.pedip_qtde,a.pedi_dt_compra,b.PEDIP_VALOR_POR,d.fabr_nome
me returns the records, I would like to group them:
To be able to group, the content of the lines must be equal. If despite the column is contained in the GROUP BY clause and the bank does not respect it is a sign that has different content between lines. You will need to remove this column from select and group by
– Reginaldo Rigo
@Reginaldorigo, the content is equal, see in the image the result, the order number is not in the query
– Harry
Select from this select. Like this: SELECT * FROM ( select ... ) A GROUP BY .. all fields that come.
– Reginaldo Rigo
Queries that have GROUP BY clause with all columns usually indicate code that needs to be rewritten. In your case, I suggest that you group orders for the same product before making the other joints. In this way, the GROUP BY clause will be kept to a minimum.
– José Diz
Is it also to group the orders for the same product if, within the reporting period, the orders for the same product are made on different days? How is the pedi_dt_purchase column declared? If as datetime, it contains only date or date and time?
– José Diz