在select(SQL Server)中选择不带from子句作为子查询

时间:2018-06-18 19:32:25

标签: sql sql-server

我有一个包含两个表的数据库,即交易和客户。 Transaction表具有交易日期,客户ID和其他交易信息。客户表具有客户ID和其他客户信息。我需要查找每个客户进行的交易计数。即使客户在一个日期内进行了两笔交易,计数也将是一笔。

我正在编写一个查询来从列中获取不同的事务计数。首先,我在子查询中使用了以下查询和from子句,但它无法正常工作。无意中,我删除了来自right join (Select Customer.customer_Id) Customer的from子句,它给了我正确的答案。我无法理解为什么?

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

结果表类似于

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

2 个答案:

答案 0 :(得分:0)

您需要按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;

答案 1 :(得分:0)

您可以使用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;

但是,这假设tran_date具有合理的格式,否则您将需要相应地使用cast/convert()函数。

现在,我将您的第一种方法重写为:

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;