CASE条件以及如何编码?

时间:2012-01-29 17:31:24

标签: sql sql-server

我在新表(表B)中创建了一个名为Number of different locations的列。此列派生自表A中的两列 - 客户和位置。

表A中的样本数据。

Customer          Location 

Mr James Smith   Los Angeles
Mr David Jones   London
Mr James Smith   Paris

那么伪代码?

[Number of Different Locations] =

CASE 
When Customer has more than one location ( count greater than 1 of for distinct customer) 
Then populate those entries as 'Y'
Else 'N' 

现在我尝试了几种方法来编写第一个条件,但它不起作用。

CASE 
When EXISTS ( select distinct customer, count ( Location ) from Table B
              group by customer)
then 'Y'
Else 'N'

我做错了什么?所有值都在结果表中显示为'Y'

4 个答案:

答案 0 :(得分:1)

SELECT   Customer, Location, [Number of different locations] = 
      CASE 
      When EXISTS ( select distinct customer, count ( Location ) from Table B
              group by customer
               having count(location)>1)
then 'Y'
Else 'N'
      END
FROM [Table]

您没有指定“有> 1”

答案 1 :(得分:1)

你真的不需要单独的子选择。这可以完全在GROUP BY子句内处理,并使用位置计数来确定是否有多个位置。

SELECT Customer
       ,  MultipleLocations = 
            CASE WHEN COUNT(Location) > 1 
                 THEN 'Y' 
                 ELSE 'N'        
            END 
FROM   YourTable
GROUP BY
       Customer

如果您的表包含具有相同位置的客户的多条记录,您可以添加DISTINCT子句以适应此目的。

SELECT Customer
       ,  MultipleLocations = 
            CASE WHEN COUNT(DISTINCT Location) > 1 
                 THEN 'Y' 
                 ELSE 'N'        
            END 
FROM   YourTable
GROUP BY
       Customer

答案 2 :(得分:1)

也许这会以另一种方式帮助它:

DECLARE @tbl TABLE
    (
        Customer VARCHAR(100),
        Location VARCHAR(100)
    )
INSERT INTO @tbl
SELECT 'Mr James Smith','Los Angeles'
UNION ALL
SELECT 'Mr David Jones','London'
UNION ALL
SELECT 'Mr James Smith','Paris'

;WITH CTE AS
(
    SELECT
        COUNT(*) OVER(PARTITION BY tbl.Customer) AS NbrOf,
        tbl.Customer,
        tbl.Location
    FROM
        @tbl AS tbl
)
SELECT
    CTE.Customer,
    CTE.Location,
    (
        CASE 
            WHEN CTE.NbrOf>1
            THEN 'Y'
            ELSE 'N'
        END
    ) AS newColumn
FROM
    CTE

答案 3 :(得分:0)

WITH TableA 
     AS
     (
      SELECT * 
        FROM (
              VALUES ('Mr James Smith', 'Los Angeles'),
                     ('Mr David Jones', 'London'),
                     ('Mr James Smith', 'Paris')
             ) AS T (Customer, Location)
     ), 
     TableACustomerTallies
     AS
     (
      SELECT Customer, COUNT(DISTINCT Location) AS Tally
        FROM TableA
       GROUP 
          BY Customer

     )
SELECT Customer, 
        'Y' AS HasMultipleLocations
  FROM TableACustomerTallies
 WHERE Tally > 1
UNION
SELECT Customer, 
        'N' AS HasMultipleLocations
  FROM TableACustomerTallies
 WHERE Tally <= 1;