我有一个查询,它给出了以下输出:
AcctName budget
Gross Salaries 232332
Basic Salaries 23123
Local Salaries 2312312
Local Travel 23424
country Travel 32242
Health care supplies 234234
Goods Supplies 3243242
您可以在此表中看到我有三个常用名称,例如Salaries
,Travel
,Supplies
及其budget
。我想查询可以给我以下结果:
AcctNAme Budget
Salaries 232323423
Travel 323232332
Supplies 232323232
budget
应为salaries
,travel
和supplies
的总和。
修改
SELECT T1.[AcctName], T0.[DebLTotal]
FROM (VALUES('Salaries'),('Travel'),('Supplies')) TT1(AcctName)
LEFT JOIN(
SELECT CASE WHEN T1.[AcctName] LIKE '%Salaries%' THEN 'Salaries'
WHEN T1.[AcctName] LIKE '%Travel%' THEN 'Travel'
WHEN T1.[AcctName] LIKE '%Supplies%' THEN 'Supplies' END AS ActNAme,
SUM(T0.[DebLTotal]) AS budget
FROM OBGT T0
INNER JOIN OACT T1 ON T0.[AcctCode] = T1.[AcctCode]
INNER JOIN OBGS T2 ON T0.[Instance] = T2.[AbsId]
GROUP BY CASE WHEN T1.[AcctName] LIKE '%Salaries%' THEN 'Salaries'
WHEN T1.[AcctName] LIKE '%Travel%' THEN 'Travel'
WHEN T1.[AcctName] LIKE '%Supplies%' THEN 'Supplies' END) TT2 ON TT1.[AcctName] = TT2.[AcctName]
答案 0 :(得分:1)
这应该可以正常工作。
select 'Salaries' as AcctName, (select sum(budget)
from myTable
where lower(AcctName) like '%salaries%') as Budget
union
select 'Travel', (select sum(budget)
from myTable
where lower(AcctName) like '%travel%')
union
select 'Supplies', (select sum(budget)
from myTable
where lower(AcctName) like '%supplies%')
您可以 test it here
我使用lower()
进行不区分大小写的比较。很多时候,这不是必需的,具体取决于您如何定义数据库Collation。
答案 1 :(得分:1)
您可以使用条件分组,如:
DECLARE @t TABLE
(
AcctName VARCHAR(100) ,
budget INT
)
INSERT INTO @t
VALUES ( 'Gross Salaries', 232332 ),
( 'Basic Salaries', 23123 ),
( 'Local Salaries', 2312312 ),
( 'Local Travel', 23424 ),
( 'country Travel', 32242 ),
( 'Health care supplies', 234234 ),
( 'Goods Supplies', 3243242 )
SELECT CASE WHEN AcctName LIKE '%Salaries%' THEN 'Salaries'
WHEN AcctName LIKE '%Travel%' THEN 'Travel'
WHEN AcctName LIKE '%Supplies%' THEN 'Supplies'
ELSE 'Other' END AS AcctNAme,
SUM(budget) AS budget
FROM @t
GROUP BY CASE WHEN AcctName LIKE '%Salaries%' THEN 'Salaries'
WHEN AcctName LIKE '%Travel%' THEN 'Travel'
WHEN AcctName LIKE '%Supplies%' THEN 'Supplies'
ELSE 'Other' END
编辑:
SELECT t.AcctNAme, l.budget
FROM (VALUES('Salaries'),('Travel'),('Supplies')) t(AcctNAme)
LEFT JOIN(
SELECT CASE WHEN AcctName LIKE '%Salaries%' THEN 'Salaries'
WHEN AcctName LIKE '%Travel%' THEN 'Travel'
WHEN AcctName LIKE '%Supplies%' THEN 'Supplies' END AS AcctNAme,
SUM(budget) AS budget
FROM @t
GROUP BY CASE WHEN AcctName LIKE '%Salaries%' THEN 'Salaries'
WHEN AcctName LIKE '%Travel%' THEN 'Travel'
WHEN AcctName LIKE '%Supplies%' THEN 'Supplies' END) l ON t.AcctNAme = l.AcctNAme
答案 2 :(得分:1)
您使用 int sumOfDigits(int n)
{
if(n<=9)
return n;
else
{
int r=0;
while(n!=0)
{
r=r+n%10;
n=n/10;
}
sumOfDigits(r);
}
}
和REVERSE
功能来反转RIGHT
示例:
ActName
您可以尝试以下代码:
SELECT RIGHT(S, CHARINDEX(' ', REVERSE(S)))FROM(
SELECT 'Health care supplies' AS S) AS A
-- Result
supplies