0

I have a SQL script that extracts sale data by agent.

cur = conn.cursor()
cur.execute("""select sales_rep,to_char(sales_date,'yyyy-mm')as month,count(*) from sale""")
report = cur.fetchall()

I am trying to see if I can pass count obtained from the output to a variable (count) and month value to another variable (month_count).

Could anyone advice on this. Thanks.

Update :

Sample Output:

Sales_Rep,Month,Count
Person1,Jan,20
Person1,Feb,15
Person1,Mar,10
Person2,Jan,8
Person2,Feb,13
Person2,Mar,15

Expected Output:

count = 20,15,108,13,15
month = jan,feb,mar,jan,feb,mar
2
  • Please show sample input and output data. Your current query should not even run, I think. Commented Dec 3, 2018 at 11:06
  • @TimBiegeleisen, I have updated my initial post. Thanks Commented Dec 3, 2018 at 11:15

1 Answer 1

1

You just need a basic group by query here:

SELECT
    sales_rep,
    TO_CHAR(sales_date, 'yyyy-mm') AS month,
    COUNT(*) AS cnt
FROM sale
GROUP BY
    sales_rep,
    TO_CHAR(sales_date, 'yyyy-mm');

Python code:

cur = conn.cursor()
cur.execute("""SELECT sales_rep, TO_CHAR(sales_date, 'yyyy-mm') AS month, COUNT(*) AS cnt FROM sale GROUP BY sales_rep, TO_CHAR(sales_date, 'yyyy-mm')""")
rows = cur.fetchall()
for row in rows:
    print("{} " + row["month"]).format(row["cnt"])
Sign up to request clarification or add additional context in comments.

2 Comments

how could I call these column separately output of this sql script. This is where I am stuck.
@scottmartin Check my updated answer. I added some Python code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.