我正在尝试找到一种方法,将计算出的行插入到基于单独总和的减去总和的SQL查询中
例如:
Name | Title | eID | Spend_Category |Jan|Feb|...|Nov|Dec|Sum of Months|
Jay | CEO | 1 | Lodging |10 |20 |...| 0 |30 | 60 |
Jay | CEO | 1 | Airlines |20 |40 |...| 0 |60 | 120 |
Jay | CEO | 1 | Auto |10 |20 |...| 0 |30 | 60 |
Paul | VP | 2 | Lodging |10 |20 |...| 0 |30 | 60 |
在另一张桌子上,我有每个员工ID的总支出。 我要做的是创建一个新行,并为每个用户(eID)创建一个新的“其他”Spend_Category,它总结该用户的所有不同支出并从总计中减去它。所以,如果杰伊的总支出为500美元
例如:
Name | Title | eID | Spend_Category |Jan|Feb|...|Nov|Dec|Sum of Months|
Jay | CEO | 1 | Lodging |10 |20 |...| 0 |30 | 60 |
Jay | CEO | 1 | Airlines |20 |40 |...| 0 |60 | 120 |
Jay | CEO | 1 | Auto |10 |20 |...| 0 |30 | 60 |
Jay | CEO | 1 | Other |...................|$500-240=$260|
Paul | VP | 2 | Lodging |10 |20 |...| 0 |30 | 60 |
...etc...
我当然乐于接受各种想法,而且我对SQL很新。这是我到目前为止所处的位置,并将欣赏该集团的专业知识。
SELECT
SC.Full_Name,
TS.Job_Title,
TS.Card_Type,
SC.Employee_ID,
SC.Genesis_Industry,
SC.May,
SC.June,
SC.July,
SC.August,
SC.September,
SC.October,
SC.November,
SC.December,
SC.January,
SC.February,
SC.March,
SC.April,
(NZ(SC.May,0)+NZ(SC.June,0)+ NZ(SC.July,0)+ NZ(SC.August,0)+NZ(SC.September,0)+NZ(SC.October,0)+NZ(SC.November,0)+NZ(SC.December,0)+NZ(SC.January,0)+NZ(SC.February,0)+NZ(SC.March,0)+NZ(SC.April,0)) AS Category_Spend,
TS.Total_Spend
FROM Spend_Category SC
left join Top_Spender TS
on SC.Employee_ID=TS.Employee_ID
答案 0 :(得分:0)
我创建了自己的快速表,并写了一个如何完成此操作的简短示例。但是,通过这个工作,我注意到,按照我写的方式,你必须知道你想要哪些类别作为自己的行项目,然后将其他类别扔进“其他”字段。
create table #test (firstname varchar(max),
category varchar(max),
jan int, feb int, mar int, apr int, may int, jun int, jul int, aug int, sep int, oct int, nov int, dec int)
insert into #test values
('Joe','Lodging',100,50,874,7852,50,50,6,0,0,0,0,0),
('Joe','Airlines',100,510,874,60,20,50,6,0,0,0,0,0),
('Joe','Auto',100,50,874,60,50,50,6,0,0,0,0,0),
('Joe','Lunch',500,50,874,60,50,50,6,0,0,500,0,0),
('Joe','Insurance',100,50,874,4111,50,50,6,0,0,0,0,0)
select
firstname,
Other = sum(case when category not in ('lodging','airlines','auto')
then yearly else 0 end)
into #tbl
from #test t
cross apply (select yearly = isnull(jan,0) + isnull(feb,0) +
isnull(mar,0) + isnull(apr,0) + isnull(may,0) + isnull(jun,0) +
isnull(jul,0) + isnull(aug,0) + isnull(sep,0) + isnull(oct,0) +
isnull(nov,0) + isnull(dec,0)) y
group by firstname
select
t.firstname,
category,
yearlyTotal
from #test t
cross apply (select yearlyTotal = isnull(jan,0) + isnull(feb,0) +
isnull(mar,0) + isnull(apr,0) + isnull(may,0) + isnull(jun,0) +
isnull(jul,0) + isnull(aug,0) + isnull(sep,0) + isnull(oct,0) +
isnull(nov,0) + isnull(dec,0)) y
where category in ('lodging','airlines','auto')
UNION
select
firstname,
'Other' as Category,
other as yearlyTotal
from #tbl t