多种情况下的情况

时间:2017-06-13 11:18:02

标签: sql tsql

我有多个表,我正在对它们执行PiCamera。我想根据某些字段以某些字母开头的条件对它们进行分组,然后按区域对它们进行分组。这就是我的方式

JOIN

上面的代码为我提供了COUNT而不考虑区域。如果我希望每个唯一SELECT CASE WHEN PNumber LIKE 'F%' THEN 'F' WHEN PNumber LIKE 'CE%' THEN 'CE' WHEN PNumber LIKE 'CXT%' THEN 'CXT' END AS p_by_type , COUNT(*) AS p_by_count FROM ( SELECT [xml_P].Id, [xml_P].PNumber, [xml_PSR].ScopeRegion, [xml_SR].RegionCode FROM [xml_P] JOIN [xml_PSR] ON [xml_P].Id = [xml_PSR].Pol JOIN [xml_SR] ON [xml_PSR].SR = [xml_SR].Id) PWithRegions GROUP BY CASE WHEN PNumber LIKE 'F%' THEN 'F' WHEN PNumber LIKE 'CE%' THEN 'CE' WHEN PNumber LIKE 'CXT%' THEN 'CXT' END GO 的每个PNumber的计数从F,CE,CXT开始,我该怎么办?那是[xml_SR].RegionCode我希望计数F,CE,CXT,然后[xml_SR].RegionCode = AMER我想要相同的等等。

执行嵌套查询:

[xml_SR].RegionCode = CH

Id,PNumber,ScopeRgion,RegionCode 1,F586,42,EMEA .. 22,CE86,42,EMEA .. 44,CXT6,42,EMEA .. 101,F56,42,EMEA .. 105,F996,43,CH .. 122,CXT186,43,CH .. 44,CXT196,43,CH .. 101,CE5556,43,CH ..

并执行完整的查询给我一个像这样的结果集:

p_by_type,p_by_count F,39 CXT,258 CE,77

我希望输出是什么

F,25,CH F,3,EMEA ..

2 个答案:

答案 0 :(得分:1)

您只需将RegionCode添加到GROUP BY即可。但是,您的查询过于复杂 - 不需要子查询:

SELECT (CASE WHEN p.PNumber LIKE 'F%' THEN 'F'
             WHEN p.PNumber LIKE 'CE%' THEN 'CE'
             WHEN p.PNumber LIKE 'CXT%' THEN 'CXT'
        END) as p_by_type,
       sr.RegionCode,
       COUNT(*) AS p_by_count
FROM xml_P p JOIN
     xml_PSR psr
     ON p.Id = psr.Pol JOIN
     xml_SR sr
     ON psr.SR = sr.Id
GROUP BY (CASE WHEN p.PNumber LIKE 'F%' THEN 'F'
               WHEN p.PNumber LIKE 'CE%' THEN 'CE'
               WHEN p.PNumber LIKE 'CXT%' THEN 'CXT'
          END),
         sr.RegionCode;

注意:

  • 表别名使查询更容易编写和阅读。
  • 不需要子查询。
  • 您应该在SELECTGROUP BY中包含您想要的区域代码。
  • 如果不需要,[等转义字符的使用会使查询混乱。

答案 1 :(得分:0)

您可以在您的选择中以及在您的组中添加RegionCode。

因此您将获得每个PNumber中每个RegionCode的计数。

SELECT
  CASE    
    WHEN PNumber LIKE 'F%' THEN 'F'
    WHEN PNumber LIKE 'CE%' THEN 'CE'
    WHEN PNumber LIKE 'CXT%' THEN 'CXT'
  END AS p_by_type
, RegionCode
, COUNT(*) AS p_by_count
FROM (
    SELECT [xml_P].Id, [xml_P].PNumber, [xml_PSR].ScopeRegion, [xml_SR].RegionCode
    FROM [xml_P]
    JOIN [xml_PSR]
    ON [xml_P].Id = [xml_PSR].Pol
    JOIN [xml_SR]
    ON [xml_PSR].SR = [xml_SR].Id) PWithRegions
GROUP BY 
  CASE
    WHEN PNumber LIKE 'F%' THEN 'F'
    WHEN PNumber LIKE 'CE%' THEN 'CE'
    WHEN PNumber LIKE 'CXT%' THEN 'CXT'
  END, RegionCode
GO