在“ - ”之前按字符串分组/基于多行创建新列

时间:2018-06-11 01:15:38

标签: sql-server

对于初学者抱歉这个可怕的头衔。我想不出一个好的。

背景:我有一个产生此输出的销售数据表:

+-------------------+---------+-------------+--+
|    AccountName    | OrderID | ShipToState |  |
+-------------------+---------+-------------+--+
| Apple-Houston     |       1 | TX          |  |
| Apple-Austin      |       2 | CA          |  |
| Apple-Austin      |       3 | NY          |  |
| Apple-Austin      |       4 | CA          |  |
| Apple-Austin      |       5 | NY          |  |
| Apple-San Antonio |       6 | NY          |  |
| Microsoft-NYC     |       7 | TX          |  |
| Microsoft-Chicago |       8 | NY          |  |
+-------------------+---------+-------------+--+

这显示了我们的销售情况以及运往何处。

我希望的最终结果是:

  1. 在“ - ”之前使用相同名称的组帐户。
  2. 显示以下每个州的销售帐户:TX,CA,NY,IL
  3. 期望的输出应该如下所示:

    +-------------+-----+-----+-----+----+
    | AccountName | CA  | TX  | NY  | IL |
    +-------------+-----+-----+-----+----+
    | Apple       | YES | YES | YES | NO |
    | Microsoft   | NO  | YES | YES | NO |
    +-------------+-----+-----+-----+----+
    

    对于第一部分,我这样做了:

    Select SUBSTRING(sd.[Account Name], 1, CHARINDEX('-',sd.[Account Name]+'-') - 1) From Sales_Data sd

    这一般情况下有效,但我不确定在引入这个问题的第二部分时它是如何工作的。

    至于第二部分,我真的很茫然。我试过这个:

    SELECT 
    SUBSTRING(sd.[Account Name], 1, CHARINDEX('-',sd.[Account Name]+'-') - 1),
      CASE WHEN sd.[Ship to State] = 'CA' THEN 'Yes' ELSE 'No' END AS CA,
      CASE WHEN sd.[Ship to State] = 'TX' THEN 'Yes' ELSE 'No' END AS TX,
      CASE WHEN sd.[Ship to State] = 'NY' THEN 'Yes' ELSE 'No' END AS NY,
      CASE WHEN sd.[Ship to State] = 'IL' THEN 'Yes' ELSE 'No' END AS IL
      FROM SALES_DATA sd
    

    但它会返回如下所示的结果:

    +--------------+-----+-----+-----+----+
    | Account Name | CA  | TX  | NY  | IL |
    +--------------+-----+-----+-----+----+
    | Apple        | no  | yes | no  | no |
    | Apple        | yes | no  | no  | no |
    | Apple        | no  | no  | yes | no |
    | Apple        | yes | no  | no  | no |
    | Apple        | no  | no  | yes | no |
    | Apple        | no  | no  | yes | no |
    | Microsoft    | no  | yes | no  | no |
    | Microsoft    | no  | no  | yes | no |
    +--------------+-----+-----+-----+----+
    

    我甚至不确定这是否可行,但如果是的话,我会感到茫然。

1 个答案:

答案 0 :(得分:1)

尝试以下SQL。

SELECT AccountName,
(case when CA > 0 then 'YES' else 'NO' end) as CA,
(case when TX > 0 then 'YES' else 'NO' end) as TX, 
(case when NY > 0 then 'YES' else 'NO' end) as NY, 
(case when IL > 0 then 'YES' else 'NO' end) as IL
FROM
(
select SUBSTRING(AccountName, 1, CHARINDEX('-', AccountName +'-') - 1) as AccountName, OrderID, ShipToState
FROM SALES_DATA) as sd
PIVOT
(
 count(OrderID)
 FOR ShipToState IN ([CA],[TX],[NY],[IL])
) AS PivotTable;