帮助SQL Server加入

时间:2011-08-29 18:48:13

标签: sql sql-server tsql join

我需要一些帮助,我正在尝试在SQL Server中创建一个视图,在我的数据库中按状态细分客户。

表1:

CustomerID, Gender, CustomerType

表2:

CustomerID, State, City, Zipcode

我希望最后的视图有以下(示例):

ID| State | Males | Females | PlatinumCustomer | GoldCustomer | SilverCustomer
1    FL      200     300           40                 200           260  
2    MO      200     400           40                 300           360

我的Genders的值为MFCustomerTypes的值为PG和{{1} }}。 任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:6)

这是一个基本的数据透视表,可以基本满足您的需求。您的示例中有一个ID列,无法从数据集中直接复制。它必须计算。

SELECT 
  State,
  SUM(CASE WHEN Gender = 'M' THEN 1 ELSE 0 END) AS Males,
  SUM(CASE WHEN Gender = 'F' THEN 1 ELSE 0 END) AS Females,
  SUM(CASE WHEN CustomerType = 'P' THEN 1 ELSE 0 END) AS PlatinumCustomer,
  SUM(CASE WHEN CustomerType = 'G' THEN 1 ELSE 0 END) AS GoldCustomer,
  SUM(CASE WHEN CustomerType = 'S' THEN 1 ELSE 0 END) AS SilverCustomer
FROM Table1 JOIN Table2 ON Table1.CustomerID = Table2.CustomerID
GROUP BY State

答案 1 :(得分:1)

试试这个

With Table1 AS
(
    Select 1 as CustomerId, 'M' Gender, 'Platinum' as CustomerType
    UNION SELECT 2, 'M', 'Platinum'
    UNION SELECT 3, 'F', 'Gold'
    UNION SELECT 4, 'M', 'Gold'
    UNION SELECT 5, 'F', 'Gold'
    UNION SELECT 6, 'M', 'Silver'
    UNION SELECT 7, 'F', 'Silver'
    UNION SELECT 8, 'M', 'Silver'
    UNION SELECT 9, 'F', 'Silver'
),
Table2 AS
(
    SELECT 1 as CustomerId, 'FL' State, NULL City, NULL ZipCode
    UNION SELECT 2, 'MO' State, NULL City, NULL ZipCode
    UNION SELECT 3, 'MO' State, NULL City, NULL ZipCode
    UNION SELECT 4, 'FL' State, NULL City, NULL ZipCode
    UNION SELECT 5, 'FL' State, NULL City, NULL ZipCode
    UNION SELECT 6, 'FL' State, NULL City, NULL ZipCode
    UNION SELECT 7, 'MO' State, NULL City, NULL ZipCode
    UNION SELECT 8, 'MO' State, NULL City, NULL ZipCode
    UNION SELECT 9, 'MO' State, NULL City, NULL ZipCode
)
Select 
    Row_Number() Over (Order By State) Id,
    State, 
    Sum (Case When Gender = 'm' then 1 else 0 end) as Males,
    Sum (Case When Gender = 'f' then 1 else 0 end) as Females,
    Sum (Case When CustomerType = 'Platinum' then 1 else 0 end) as PlatinumCustomer,
    Sum (Case When CustomerType = 'Gold' then 1 else 0 end) as GoldCustomer,
    Sum (Case When CustomerType = 'Silver' then 1 else 0 end) as SilverCustomer
From Table1 
    Inner Join Table2 
    on Table1.CustomerId = Table2.CustomerId
Group By State