按条款分组

时间:2013-09-04 06:14:16

标签: sql-server tsql group-by case-when

我有以下表格Issue,IssueStatus和CustomTable(CT)。以下是相同的数据

Issue:                       Issuestatus:                    CT

Issue|pkey|issuestatus       id | pname                     Issue|Referred
----------------------------------------------------------------------------
100     T-1  1                  1   Open                       100     NULL
200     T-2  2                  2   Closed                     200     NULL 
300     T-3  3                  3   Acknowledged               700     Dev
400     T-4  4                  4   In Progress                800     QA
500     T-5  1                  5   Referred                   800     NULL 
600     T-6  2                                                 400     NULL
700     T-7  5                                                 500     NULL   
800     T-8  5                                                 700     NULL

我需要输出如下

pname      |  Count
Open           2
Closed         2
Acknowledged   1
In Progress    1
Dev            1 
QA             1

因此,如果您看到,需要按issuestatus进行分组并获得pkey的计数,但是当issuestatus为“已推荐”时,您需要查看CT表并获取组中的相应引用列文本。 CT中的问题与问题表中的问题有关。

这是我尝试过的,但不是正确的输出

select pname = case 
    when pname='Referred' then CT.Referred 
    else pname end,
    COUNT(pkey) 
from  CT,issue a,issuestatus
where a.issuestatus=issuestatus.id and a.issue=CT.ISSUE 
group by pname,CT.Referred

3 个答案:

答案 0 :(得分:2)

我测试了以下查询,确切地给出了你想要的内容

试试吧

WITH T1 AS (
  SELECT (CASE WHEN pname='Referred' THEN Referred ELSE pname END)AS [pn]
  FROM (SELECT i.Issue,c.Referred,iss.pname
        FROM Issue i
        INNER JOIN IssueStatus iss ON i.issuestatus=iss.id
        LEFT OUTER JOIN CT c ON c.Issue=i.Issue
       ) t
)


SELECT pn,count(*) AS cnt
FROM T1
WHERE pn IS NOT NULL
GROUP BY pn
ORDER BY cnt DESC

以下是SQLFiddle

答案 1 :(得分:1)

试试这个

 SELECT pname, COUNT(pname)
    FROM (SELECT (CASE WHEN Pname='Referred'  THEN CT.referred else st.pname END)AS pname
            FROM Issue a JOIN IssueStatus st
            ON a.issuestatus = st.id LEFT OUTER JOIN CT
            ON a.Issue = CT.Issue) tbl
    GROUP BY pname
    HAVING pname IS NOT NULL;

以下是SQLFiddle

答案 2 :(得分:0)

试试这个。没有测试它,因为没有测试数据脚本。

   select case when pname='Referred' then CT.Referred else pname end pname, COUNT(*) cnt
    from  CT,issue a,issuestatus
    where a.issuestatus=issuestatus.id and a.issue=CT.ISSUE 
    group by case when pname='Referred' then CT.Referred else pname end