Skip to content
Advertisement

How to calculate rows count in where statement in sql?

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:

  2. And the count of the rows (without the first filter)

So I wrote this query:

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

I mean the “some of many”

Advertisement

Answer

First aggregate in payment and then join to order:

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:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement