PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

[FIXED] How to calculate rows count in where statement in sql?

 October 29, 2022     group-by, left-join, sql, sql-server, tsql     No comments   

Issue

I have two tables in SQL Server:

  • order (columns: order_id, payment_id)
  • payment (columns: payment_id, is_pay)

I want to get all orders with two more properties:

  1. How many rows where is_pay is 1:

     where payment_id = <...> payment.is_pay = 1
    
  2. And the count of the rows (without the first filter)

     select count(*) 
     from payment 
     where payment_id = <...>
    

So I wrote this query:

select 
    *, 
    (select count(1) from payment p 
     where p.payment_id = o.payment_id and p.is_pay = 1) as total 
from 
    order o

The problem is how to calculate the rows without the is_pay = 1?

I mean the "some of many"


Solution

First aggregate in payment and then join to order:

SELECT o.*, p.total_pay, p.total
FROM [order] o 
LEFT JOIN (
  SELECT payment_id, SUM(is_pay) total_pay, COUNT(*) total
  FROM payment
  GROUP BY payment_id
) p ON p.payment_id = o.payment_id;

Change LEFT to INNER join if all orders have at least 1 payment.
Also, if is_pay's data type is BIT, change SUM(is_pay) to:

SUM(CASE WHEN is_pay = 1 THEN 1 ELSE 0 END)


Answered By - forpas
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing