1

我有一个 SQL Server 2005 表,其中列出了客户及其订单行,如下所示...

Cust  | Code 
Cust1   N001
Cust2   N001
Cust2   N003
Cust2   N004
Cust3   N001
Cust3   N002
Cust3   N003
Cust3   N004

我需要结果来列出每个客户(一次)以及他们是否订购了 N002 和 N004 之间的任何物品。因此,结果看起来像这样......

Cust  | Ordered?
Cust1   False
Cust2   True
Cust3   True

我尝试了 All / ANY 等的各种组合。我得到的最接近的是使用两个查询。首先,我将添加以下内容以在每一行的末尾添加一个真/假语句......

SELECT 
    Cust, Code, 
    CASE 
        WHEN Code BETWEEN 'N002' AND 'N004' THEN 'True' 
        ELSE 'False' 
    END AS Expr1 

这给出了以下...

Cust  | Code | EXPR1
Cust1   N001   FALSE
Cust2   N001   FALSE
Cust2   N003   TRUE
Cust2   N004   TRUE
Cust3   N001   FALSE
Cust3   N002   TRUE
Cust3   N003   TRUE
Cust3   N004   TRUE

然后使用第二个查询并对我得到的结果进行分组

Cust  | Ordered?
Cust1   False
Cust2   False
Cust2   True
Cust3   False
Cust3   True

那么任何人都可以帮助实现简单...

Cust  | Ordered?
Cust1   False
Cust2   True
Cust3   True
4

2 回答 2

1

我假设您有某种客户表。如果是这样,这可以通过以下方式轻松实现:

SELECT Customer.id, 
CASE WHEN DidOrder.customerId IS NOT NULL THEN true ELSE false END as ordered
FROM Customer
LEFT JOIN (SELECT DISTINCT customerId
           FROM OrderLine
           WHERE code >= 'N002' 
           AND code < 'N005') DidOrder
ON DidOrder.customerId = Customer.id

这将检查所有客户,无论他们是否有订单。

于 2012-05-14T16:33:52.200 回答
0

我的解决方案是添加一个变量,指定值是否在范围内,然后在 case 语句中检查:

SELECT Cust,
       (case when sum(inrange) > 0 THEN 'True' ELSE 'False' END) AS count
from (select t.*,
             (case when code between 'N002' and 'N004' then 1 else 0 end) as inrange
      from t
     ) t
group by cust

如果您不关心代码的可读性,您实际上可以将两个 case 语句合二为一。

于 2012-05-14T16:30:00.257 回答