0

下面的 SQL 几乎完全符合我的要求。

SELECT p.ProductNumber "Plan Number",
       p.Name,
       p.price         "Monthly Rate",
       count(*)        "Group",
       '0'             "Direct Debit"
FROM   contact c,
       product p
WHERE  c.integ_schemeid = p.ProductId
       AND c.ParentCustomerId IS NOT NULL
GROUP  BY p.ProductNumber,
          p.Name,
          p.price
UNION
SELECT p.ProductNumber "Plan Number",
       p.Name,
       p.price         "Monthly Rate",
       '0'             "Group",
       count(*)        "Direct Debit"
FROM   contact c,
       product p
WHERE  c.integ_schemeid = p.ProductId
       AND c.ParentCustomerId IS NULL
GROUP  BY p.ProductNumber,
          p.Name,
          p.price 

结果:

在此处输入图像描述

我希望每个计划有一行,将组和直接借记值放在一行中。

这在 T-SQL 中可能吗?

4

2 回答 2

2

尝试

select p.ProductNumber "Plan Number",p.Name,p.price "Monthly Rate",
    count(CASE WHEN c.ParentCustomerId IS NOT NULL THEN 1 END) "Group", 
    count(CASE WHEN c.ParentCustomerId IS NULL THEN 1 END) "Direct Debit"
from contact c,product p 
where c.integ_schemeid = p.ProductId
group by p.ProductNumber,p.Name,p.price

在 失败时CASE WHENCASE将返回NULL,并且COUNT不“计算”NULL值。是1一个随机值。它只意味着“不是NULL”。您可以使用'X', 'Foo', 0, -1...

于 2013-09-10T09:40:47.627 回答
0

OK 这个查询假设每个名字有 2 行,所以我会使用内部连接

select t1.[Plan Number],t1.Name, t1.[Monthly Rate],t1.Group,t2.[Direct Debit] from
(
select p.ProductNumber "Plan Number",p.Name,p.price "Monthly Rate",count(*) "Group", '0' "Direct Debit"
from contact c,product p 
where c.integ_schemeid = p.ProductId
and c.ParentCustomerId is not null
group by p.ProductNumber,p.Name,p.price
)t1
inner join
(
select p.ProductNumber "Plan Number",p.Name,p.price "Monthly Rate", '0' "Group", count(*) "Direct Debit"
from contact c,product p 
where c.integ_schemeid = p.ProductId
and c.ParentCustomerId is null
group by p.ProductNumber,p.Name,p.price) t2
on t1.[Plan Number] = t2.[Plan Number] and t1.name=t2.name and t1.[Monthly Rate] = t2.[Monthly Rate]

在此查询中,我使用相同的计算然后加入另一个表,您可以修改要过滤的列,但对于列组,我使用了上层查询,而对于直接借记列,我使用了下层查询

于 2013-09-10T09:44:32.637 回答