像这样查询:
select coalesce(sp.name, 'SUM') COLLATE DATABASE_DEFAULT as name,
count(*) as [count],
(CASE WHEN sp.amounts like '%;' THEN SUBSTRING(sp.amounts,0,CHARINDEX(';',sp.amounts)) ELSE sp.amounts END) - cms.comm as [price],
cms.comm as comm,
ISNULL(MAX(fixed_amount),0.00) as ac,
(cms.comm - ISNULL(MAX(fixed_amount),0.00)) as [mo],
(((CASE WHEN sp.amounts like '%;' THEN SUBSTRING(sp.amounts,0,CHARINDEX(';',sp.amounts)) ELSE sp.amounts END) - cms.comm) + (cms.comm - ISNULL(MAX(fixed_amount),0.00))) as [hgf],
MAX(cms.[cc])*COUNT(*) as [zk],
(CASE WHEN sp.amounts like '%;' THEN SUBSTRING(sp.amounts,0,CHARINDEX(';',sp.amounts)) ELSE sp.amounts END) amount
,(count(*)) * ((((CASE WHEN sp.amounts like '%;' THEN SUBSTRING(sp.amounts,0,CHARINDEX(';',sp.amounts)) ELSE sp.amounts END) - cms.comm) + (cms.comm - ISNULL(MAX(fixed_amount),0.00)))) as [sg]
from auth
inner join sp on sp.id = auth.p_id
left join c on auth.p_id = c.p_id and c.a_id = @a_id and CAST(GETDATE() as DATE) between [start_date] and end_date
outer apply (SELECT .....) cms
WHERE ...
group by grouping sets( (sp.name,c_id,sp.amounts,cms.comm), (c_id))
查询的响应是:
name count price comm a_comm mo hgf sg
a1 633 14.4 0.6 0.6 0 14.4 9115.2
a2 1858 19.15 0.85 1.06 -0.21 18.94 35190.52
a3 362 19.1 0.9 1.06 -0.16 18.94 6856.28
SUM 2853 NULL NULL 2.72 NULL NULL NULL
b1 4 97.5 2.5 0 2.5 100 400
b2 1242 14.625 0.375 0 0.375 15 18630
b3 1736 19.5 0.5 0 0.5 20 34720
SUM 2982 NULL NULL 0 NULL NULL NULL
查询工作得很完美,我所拥有的唯一问题就是不计算我计算的字段并带来null。例如:(hgf,mo等)。如何总结那些领域?输出必须如下:
name count price comm a_comm mo hgf sg
a1 633 14.4 0.6 0.6 0 14.4 9115.2
a2 1858 19.15 0.85 1.06 -0.21 18.94 35190.52
a3 362 19.1 0.9 1.06 -0.16 18.94 6856.28
SUM 2853 52.65 2.35 2.72 -0.37 52.28 51162.01
b1 4 97.5 2.5 0 2.5 100 400
b2 1242 14.625 0.375 0 0.375 15 18630
b3 1736 19.5 0.5 0 0.5 20 34720
SUM 2982 131.625 3.375 0 3.375 135 53750
答案 0 :(得分:0)
所有NULL结果都归因于计算中使用的字段中的NULLS,这些字段不是由ISNULL处理的。
comm
为NULL,因此mo
为comm
的计算结果为空。