Transact-SQL选择查询提供重复值

时间:2017-12-29 07:35:13

标签: sql tsql

首先,谢谢你花时间看这个。

我正在尝试从3个表中收集数据,并制作一个参考图表,允许最终用户查看存储的数据。

基本上我这个例子有3个表: 用户:

USER_PK USER_ID USER_NAME
1   10000       Bob
2   10001       Sally
3   10003       Joe
4   10004       Susan

skill_type添加:

SKILL_PK    SKILL_NAME
11  Point of Sale
22  Digital Sales
33  Customer Service
44  Specialist Support

SKILL_ASSOCIATION:

SKILL_ASSOC_PK  SKILL_PK    USER_PK START_DATE  STOP_DATE   Priority
99  11  1   36526   500000  2
88  11  2   36527   500000  3
77  22  1   36526   500000  3
66  33  3   36528   500000  1
55  44  4   36525   500000  1
444 33  4   36525   500000  4

(我知道我可能已经破坏了一些规则,我在SQL Express中编写了这些数据,但它只是一个例子,并不代表我正在使用的真实数据)

我的选择查询为每个USER返回包含多行的不需要的结果: 语句:

 SELECT USERS.[USER_NAME], USERS.[USER_ID], 
    (CASE WHEN ST.SKILL_NAME ='Point of Sale' Then  SA.[PRIORITY] END) AS 'POS', 

    (CASE WHEN ST.SKILL_NAME ='Digital Sales' Then  SA.[PRIORITY] END) AS 'DS',
    (CASE WHEN ST.SKILL_NAME ='Customer Service' Then  SA.[PRIORITY] END) AS 'CS',
    (CASE WHEN ST.SKILL_NAME ='Specialist Support' Then  SA.[PRIORITY] END) AS 'Spec'
    FROM USERS
    INNER JOIN [dbo].[SKILL_ASSOCIATION] AS SA ON SA.USER_PK = USERS.USER_PK
    INNER JOIN SKILL_TYPE AS ST ON ST.SKILL_PK = SA.SKILL_PK

结果:

USER_NAME   USER_ID POS DS  CS  Spec
Bob 10000       2   NULL    NULL    NULL
Sally   10001       3   NULL    NULL    NULL
Bob 10000       NULL    3   NULL    NULL
Joe 10003       NULL    NULL    1   NULL
Susan   10004       NULL    NULL    NULL    1
Susan   10004       NULL    NULL    4   NULL

我尝试过使用不同的结果。 期望的结果:

NAME    ID  POS DS  CS  Spec
Bob     1   2   3       
Sally   2   3           
Joe                 1
Susan               4   1

我对此SQL Server的查询访问非常有限,无法创建/修改或删除它以实现我的目标。

非常感谢任何指导!

谢谢, 史蒂芬

1 个答案:

答案 0 :(得分:1)

您的预期输出意味着用户聚合以及获取每个MAX表达式的CASE应该有效:

SELECT
    u.[USER_NAME],
    u.[USER_ID], 
    MAX(CASE WHEN ST.SKILL_NAME = 'Point of Sale' THEN SA.[PRIORITY] END) AS POS, 
    MAX(CASE WHEN ST.SKILL_NAME = 'Digital Sales' THEN SA.[PRIORITY] END) AS DS,
    MAX(CASE WHEN ST.SKILL_NAME = 'Customer Service' THEN SA.[PRIORITY] END) AS CS,
    MAX(CASE WHEN ST.SKILL_NAME = 'Specialist Support' THEN SA.[PRIORITY] END) AS Spec
FROM USERS u
INNER JOIN [dbo].[SKILL_ASSOCIATION] AS SA
    ON SA.USER_PK = u.USER_PK
INNER JOIN SKILL_TYPE AS ST
    ON ST.SKILL_PK = SA.SKILL_PK
GROUP BY
    u.[USER_NAME],
    u.[USER_ID];