简体   繁体   中英

Select without from clause as subquery in select (SQL Server)

I have a database with two tables, Transactions and Customer. The Transaction table has transaction dates, Customer ID, and other transaction information. The customer table has Customer ID and other customer information. I need to find a count of transactions made by each customer. Even if a customer made two transactions in one single date, the count will be one.

I was writing a query to get the distinct count of transactions from a column. At first, I used the following query with a from clause in the subquery but it was not working. Accidentally, I removed the from clause, right join (Select Customer.customer_Id) Customer , and it gave me the right answer. I am not able to understand why?

Select 
   Customer_Name as [Customer Name], Gender,
   (select COUNT(distinct tran_date) from Transactions
        right join (Select Customer.customer_Id) Customer
        on Transactions.cust_id = Customer.customer_Id) as [Basket Count]
from Customer

The result table is something like

+---------------+--------+--------------+
| Customer Name | Gender | Basket Count |
+---------------+--------+--------------+
| Bob           | Male   |            2 |
| Jenny         | Female |            3 |
| Max           | Male   |            0 |
+---------------+--------+--------------+

You need to group you count by cust_id:

WITH
    aset
    AS
        (  SELECT COUNT (DISTINCT tran_date) trans_count, cust_id
             FROM transactions
         GROUP BY cust_id)
SELECT *
  FROM aset INNER JOIN customer ON cust_id = customer_id;

You can use apply :

select c.*, t.Nooftrans
from customer c outer apply (
     select count(distinct t.cust_id) as [Basket Count]
     from Transactions t
     where t.cust_id = c.customer_Id
     group by t.tran_date;
) t;

However, this assumes tran_date has reasonable format else you would need to use cast/convert() function accordingly.

Now, i would re-write your first approach as :

select c.*,
          (select COUNT(distinct t.cust_id) 
           from Transactions t
           where t.cust_id = c.customer_Id
           group by t.tran_date
          ) as [Basket Count]
from Customer c;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM