Home > Blockchain >  SumIIF Access Query
SumIIF Access Query

Time:11-05

I am struggling to get the desired results i need using an Access query, and was wondering if what i was looking to do was actually achievable in one query, or whether i would need two queries and then export to Excel and interrogate the results there.

I've a table with a number of columns, i am specifically looking at three columns

Row Type - this will either be populated with A or U Account Number - there will be potentially multiple instances of account number within the table. Although only once against row type "A", and multiple on row type "U" Value - a currency field. At Account number level, the sum of "U" row, should equal the "A" value

I am looking to produce a query that will list three things.

[Account Number]
Sum of [Value] when [RowType] = "U"
[Value] when [RowType] = "A"

Would i need to create a new column in my table to generate a value for the requirement "Sum of Value when 'U')

I've tried SUM(IIF([ROWTYPE]='U',[Value],0)) - but that doesn't seem to work.

I've also tried to use the builder within the Query to replicate the same, but again that also doesn't seem to work.

If all else fails i'm content to have to run two queries in Access and then join Excel, but i tihnk for my own learning and knowledge it would be good to know if what i am trying to do is possible.

I was hoping this is possible to compile in Access, but my knowledge of the application is seriously lacking, and despite looking on the MS Access support pages, and also some of the response on the StackOverflow forums, i still can't get my head around what i need to do.

Example of the data

Row Type Account ID Value
A 123456789 50.00
U 123456789 30.00
U 123456789 20.00
A 987654321 100.00
U 987654321 80.00
U 987654321 20.00

The data has been loaded into Access, table called "TEST"

This is the SQL i've got, but doesn't give me the desired results.

SELECT [TEST].[ROW TYPE], SUM([TEST].[VALUE]) AS [TEST].[ACCOUNT ID]
FROM [TEST]
GROUP BY [TEST].[ROW TYPE], [TEST].[ACCOUNTID]

When the query generates, would hope to see two rows, one for each account number. Three row - Account Number Sum Value (where row is U) Value (Where row is A)

I currently get 4 rows in the query. Two results for each account number, one result is the Value when Row Type = A, the other when Row Type = U.

CodePudding user response:

I guess this is what you are after:

SELECT 
    [Account ID], 
    Sum(IIf([Row Type]="A",[Value],0)) AS A, 
    Sum(IIf([Row Type]="U",[Value],0)) AS U
FROM 
    TEST
GROUP BY 
    [Account ID];

Output:

Account ID A U
123456789 50,00 50,00
987654321 100,00 100,00
  • Related