0

I am trying to do a count of invoices by country within region. Below is a view of my table structure and required output. I have tried to do a basic view (not looking at CustomerArea yet as I want to get the basics right first) of this but cannot get into a nested mode.

enter image description here

SELECT Customerregion, COUNT(InvoiceNo ) AS CountCol1
FROM [Data-Warehouse].[dbo].[Master]
WHERE Customerregion='Europe'
GROUP BY Customerregion, InvoiceNo

Below is a view of the output for Europe only based on the above?

CustomerArea    CustomerRegion  InvoiceNo
Romania Europe  INV001
Romania Europe  INV002
Netherlands Europe  INV003
Netherlands Europe  INV003
Netherlands Europe  INV003
Netherlands Europe  INV004
Italy   Europe  INV005
Italy   Europe  INV005

enter image description here

8
  • 2
    Why are you grouping by the InvoiceNo as well? Commented Jul 26, 2022 at 8:59
  • 3
    And why are you grouping by customerregion if you restrict you result to one single customerregion Commented Jul 26, 2022 at 9:00
  • Just GROUP BY Customerregion should do it. Commented Jul 26, 2022 at 9:01
  • Thank you derpirscher, you are right - that can be removed. There will be multiples area and I added the clause to try and get to a result. Commented Jul 26, 2022 at 9:02
  • 1
    Please don't show your sample data as image, but as text. If it was text then we could copy/paste it to create a temporary table and try out your query, correct it and then provide you with an answer. But since it is in an image, we would have to type over all your sample data, that is not our job but yours. Thank you Commented Jul 26, 2022 at 9:22

1 Answer 1

1

I would imagine all you need is this. Once you have this data you can count the totals for a region and also do a grand total in the calling code.

enter image description here

DROP TABLE IF EXISTS #DataTable;

CREATE TABLE #DataTable (
    CustomerArea VARCHAR(20),
    CustomerRegion VARCHAR(20),
    InvoiceNo VARCHAR(6)
);

INSERT INTO #DataTable (CustomerArea, CustomerRegion, InvoiceNo)
VALUES
('Romania', 'Europe', 'INV001'),
('Romania', 'Europe', 'INV002'),
('Netherlands', 'Europe', 'INV003'),
('Netherlands', 'Europe', 'INV003'),
('Netherlands', 'Europe', 'INV003'),
('Netherlands', 'Europe', 'INV004'),
('Italy', 'Europe', 'INV005'),
('Italy', 'Europe', 'INV005');

SELECT CustomerRegion, CustomerArea, COUNT(*) AS NumberOfInvoices
FROM #DataTable
GROUP BY CustomerArea, CustomerRegion
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Andrew - I get totally where it is going wrong now - thank you again. So, what I was trying to get to ultimately is what you produced, but clearly I got myself confused very quickly earlier in the play. Overthinking it probably, I don't know. Cheers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.