1 select with two columns

Asked

Viewed 206 times

0

Well, I’m performing a select between two dates that returns me two values.

  1. Quantity of purchases paid in CASH.

  2. Amount of purchases paid by credit card.

I’m doing it this way,

SELECT COUNT(FORMA_PAGAMENTO) AS 'DINHEIRO' FROM ESTOQUE WHERE FORMA_PAGAMENTO = 'dinheiro' AND DATA BETWEEN '2020-01-01' AND '2020-02-13' 
UNION   
SELECT (COUNT(FORMA_PAGAMENTO) AS 'CARTÃO DE CREDITO' FROM ESTOQUE WHERE FORMA_PAGAMENTO = 'Cartão de Crédito' AND DATA BETWEEN '2020-01-01' AND '2020-02-13';

The problem is that it’s returning me the two values in the same column, and I need it to be in different fields:

**DINHEIRO**      **CARTÃO DE CREDITO** 

    X                     Y

I did several searches and did not find anything related. The table that is being performed the select has no relationship.

  • As the best answer has already been chosen, I will give just a hint from the forum. Your question tags are "javascript" and "php", but it only concerns SQL derivatives.

2 answers

1


It can be as follows:

SELECT (
    SELECT COUNT(FORMA_PAGAMENTO)
    FROM ESTOQUE
    WHERE FORMA_PAGAMENTO = 'dinheiro'
    AND DATA BETWEEN '2020-01-01' AND '2020-02-13' 
) AS 'DINHEIRO',
(
    SELECT (COUNT(FORMA_PAGAMENTO))
    FROM ESTOQUE
    WHERE FORMA_PAGAMENTO = 'Cartão de Crédito'
    AND DATA BETWEEN '2020-01-01' AND '2020-02-13'
) AS 'CARTÃO DE CREDITO'
  • Dude, I hadn’t thought of it that way, and it turns out to be the same result. Thank you very much, too.

1

As the date range and the same, you can make a SUM using a CASE WHEN , this way you get the results in separate columns. According to what you posted, the query would look like this:

SELECT SUM(case when FORMA_PAGAMENTO = 'dinheiro' then 1 else 0 end) as dinheiro, 
 SUM(case when FORMA_PAGAMENTO = 'Cartão de Crédito' then 1 else 0 end) as cartao
from ESTOQUE WHERE DATA BETWEEN '2020-01-01' AND '2020-02-13'
  • Man, from the bottom of my heart thank you very much. That was exactly the result I needed and it worked. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.