以下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中是否可行?
答案 0 :(得分: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 WHEN
失败,CASE
将返回NULL
,COUNT
不会“计算”NULL
值。 1
是随机值。它只表示“不NULL
”。您可以使用'X'
,'Foo'
,0
,-1
......
答案 1 :(得分:0)
确定此查询假定每个名称都有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]
在这个查询中我使用相同的计算然后连接到另一个表,你可以修改你想要过滤的列但是对于列组我使用了上层查询和列直接借记我使用了较低的查询