简体   繁体   中英

SQL Select rows based on distinct column value

I'm trying to return postcode data for every country in our order table, this should be a straightforward query but I can't quite get it to work. The query executes fine but every row of the result is just:

  • POSTCODE | COUNTRY | id < the country id

My query is as follows:

SELECT 'POSTCODE' as billing_postcode, 'COUNTRY' as Title, billing_country_id
FROM [DB].[dbo].[Order]
INNER JOIN [DB].[dbo].[Country]
ON country_id = billing_country_id
GROUP BY billing_country_id

Below is an example of the output that I'm getting: -

在此处输入图片说明

Why is it not returning the postcode + country? Can anyone see what I've done wrong here?

Thanks

edit*

Basic Order table structure:

OrderId | billing_postcode | billing_country_id

Basic Country table structure:

country_id | Title

You've selected the string PostCode and Country not the actual columns.

SELECT POSTCODE as 'billing_postcode', COUNTRY as 'Title', billing_country_id
FROM [DB].[dbo].[Order]
INNER JOIN [DB].[dbo].[Country]
ON country_id = billing_country_id
GROUP BY billing_country_id

From your edit it seems that you need to switch the columns/alias around:

SELECT billing_postcode AS 'POSTCODE', Title as 'Country', billing_country_id
FROM [DB].[dbo].[Order]
INNER JOIN [DB].[dbo].[Country]
ON country_id = billing_country_id

Do like this. Remove apostrophes from column name and instead use it in alias part

SELECT POSTCODE as 'billing_postcode', COUNTRY as 'Title', billing_country_id
FROM [DB].[dbo].[Order]
INNER JOIN [DB].[dbo].[Country]
ON country_id = billing_country_id
GROUP BY billing_country_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM