Home > Enterprise >  SQL adding 2 query's to make one
SQL adding 2 query's to make one

Time:05-27

This is the data I'm working with in my SQL database:

Symbol | Close_Below
  AAPL       1        
  TSLA       0                
  AAPl       0
  AAPL       1        
  SPY        0                
  TSLA       1      
  SPY        0                
  AAPL       1 

SQL Query I'm using to count how many times a symbol is in the database:

SELECT Symbol, count(*) as SymbolCount FROM data GROUP BY Symbol;

Output:

Symbol | SymbolCount 
  AAPL       4        
  TSLA       2                
  SPY        2

Another SQL Query I'm using to sum all the 1's for each symbol:

SELECT  Symbol, SUM(Close_Below) as Close_Below_Sum FROM data GROUP BY Symbol;

Output:

Symbol | Close_Below_Sum 
  AAPL        3        
  TSLA        1                
  SPY         0

How would you go about getting the query to show the percentage of how many 1's to the symbol count for each symbol? Example below.

Desired Output:

Symbol | Perc
  AAPL    0.75        
  TSLA    0.50                
  SPY     0.00

CodePudding user response:

SELECT SYMBOL, AVG(Close_Below) AS PERC FROM DATA GROUP BY SYMBOL;

Output:

SYMBOL  PERC
AAPL    0.75
SPY     0.00
TSLA    0.50
  • Related