我在为查询解决方案而苦苦挣扎,任何帮助将不胜感激,最终我将自己与模板捆绑在一起,我相信肯定有一种更简单的方法。
我有一个数据库,当前产生以下结果-这是因为它没有联接或生产。
Acc No | prod No | Product Type | product Cost
12345678 1 Red Toy £100
12345678 2 Blue Toy £150
12345678 3 White Toy £300
12398654 1 White Toy £300
12398765 1 Red Toy £100
每个帐户我只希望一行,但不想丢失信息。我还想要一些款项。希望下面的内容可以显示我的意思,尽管会有更多的列:
Acc No | Prod total | cost | Prod1type | Prod1cost |prod2typ
12345678 3 £550 Red Toy £100 BlueToy
12398654 1 £300 White Toy £300 Null
我希望这能解释它。我知道我最终将获得更多专栏,但这将使我的生活变得如此轻松。
任何帮助将不胜感激,
预先感谢
答案 0 :(得分:0)
无需考虑添加ProdType
,就可以使用此查询。
假设表中每行只有1个产品。
select acc_no, count(*) as prod_total, sum(cost) as total_cost
from table
group by acc_no
order by acc_no asc
获得所有ProdType
的核心响应acc_no,您可以使用
select distinct prodtype
from table
where acc_no='exact_number'
答案 1 :(得分:0)
您可以使用多个case语句来获得预期的输出。
创建示例数据:
select 12345678 as Accno , 1 as prodno, 'Red Toy' as Producttype , 100 as Cost into #temp union all
select 12345678 as Accno , 2 as prodno, 'Blue Toy' as Producttype , 150 as Cost union all
select 12345678 as Accno , 3 as prodno, 'White Toy' as Producttype , 300 as Cost union all
select 12398654 as Accno , 1 as prodno, 'White Toy' as Producttype , 300 as Cost union all
select 12398765 as Accno , 1 as prodno, 'Red Toy' as Producttype , 100 as Cost
查询:
select accno, count(distinct prodno) Prodtotal, sum(cost) totalCost, max(case when prodno = 1 then Producttype end ) Product1type,
sum (case when prodno = 1 then cost end) Product1cost, max(case when prodno = 2 then Producttype end ) Product2type,
sum (case when prodno = 2 then cost end) Product2cost,max(case when prodno = 3 then Producttype end ) Product3type,
sum (case when prodno = 3 then cost end) Product3cost from #temp
group by accno
输出:
格式可能会稍有不同,但是我认为这是您的预期输出。
accno Prodtotal totalCost Product1type Product1cost Product2type Product2cost Product3type Product3cost
12345678 3 550 Red Toy 100 Blue Toy 150 White Toy 300
12398654 1 300 White Toy 300 NULL NULL NULL NULL
12398765 1 100 Red Toy 100 NULL NULL NULL NULL