SQL SELECT multiple columns into one - sql

I have this query in SQL Server 2008:
SELECT Id, Year, Manufacturer, Model
FROM Table
and I need something like this...
SELECT Id, (Year + [space] + Manufacturer + [space] + Model) AS MyColumn
FROM Table
How can I get this result?

I think all integer or numeric data types you need convert to String data type. When you can create your new column.
Query:
SELECT Id, (Cast([Year] as varchar(4)) + ' ' + Manufacturer + ' ' + Model) AS MyColumn
FROM Tablename

just use ' '
SELECT Id, ([Year] + ' ' + Manufacturer + ' ' + Model) AS MyColumn
FROM Tablename

Related

Manipulating duplicate values?

I have a table, with an ID, FirstName & Lastname.
I'm selecting that using the following query:
SELECT USER_ID as [ID], First_P + ' ' + Last_P as FullName FROM Persons
It's working fine. I'm basically having a list of ID's and full names.
Full names could be the same. How is it possible for me to find them and add the ID on the Full name cell as well? only when the names are the same.
Example:
1 John Wick (1)
50 John Wick (50)
I haven't found any similar questions to be honest, at least not for MSSQL. So If there are any, feel free to link me.
please take a look my answer. I used nested query to identify number of duplicated names
SELECT
ID,
IIF(NUMBEROFDUPS =1, NAME, CONCAT(NAME, ' (', ID, ')')) AS NAME
FROM
(
SELECT
ID,
CONCAT(First_P, ' ', Last_P) AS NAME,
COUNT(*) OVER (PARTITION BY First_P,Last_P) AS NUMBEROFDUPS
FROM
Table1
) tmp;
You can use outer apply to group the items via First_P + ' ' + Last_P
and then add case for multiple items.
The select stuff should look like:
SELECT USER_ID as [ID], p1.First_P + ' ' + p1.Last_P + case when cnt.FullName is not null
then '(' + p2.[sum] + ')' else '' end as FullName FROM Persons p1
outer apply (select First_P + ' ' + Last_P as FullName,count(1) as [sum]
from Persons p2
where p2.First_P + ' ' + p2.Last_P = p1.First_P + ' ' + p1.Last_P
group by First_P + ' ' + Last_P
having count(1) > 1) cnt

SQL Server : multiply column with alias name in select list [duplicate]

This question already has answers here:
Reference an alias elsewhere in the SELECT list
(3 answers)
Closed 4 years ago.
I have a select list in my query like this:
SELECT
COUNT(*) OVER () AS TotalRowsFound,
MIN(t.Title) AS Title,
t.ItemID, ' + #selectedColumn + ' as SelectedColumnSales ' + ',
t.CurrentPrice,
(t.CurrentPrice * t.SelectedColumnSales) as TotalRevenuePerItem
FROM
dbo.SearchedUserItems t
The part of the query that I'm having problem with is the following:
(t.CurrentPrice * t.SelectedColumnSales) as TotalRevenuePerItem
In the select list... The "SelectedColumnSales" can be a different column based on what I pass into the query like following:
DECLARE #selectedColumn NVARCHAR(500)
IF(#SelectedRange=7)
SET #selectedColumn = 't.SevenDaySales'
ELSE IF (#SelectedRange=14)
SET #selectedColumn='t.FourteenDaySales'
ELSE IF (#SelectedRange=21)
SET #selectedColumn='t.TwentyOneDaySales'
ELSE IF (#SelectedRange=30)
SET #selectedColumn='t.ThirtyDaySales'
Now to get revenue per item column I need to multiply these two like above, but the query throws this error:
Inner exception: SqlException: Invalid column name 'SelectedColumnSales'.
How can I multiply the dynamic column with the static column in the select list?
Can someone help me out?
if you're writing a dynamic query, which it looks like you are, you can just put the variable in your equation
declare #sql nvarchar(max)
set #sql = 'select
COUNT(*) OVER () AS TotalRowsFound,
MIN(t.Title) AS Title
, t.ItemID
,' + #selectedColumn + ' as SelectedColumnSales ' +
', t.CurrentPrice
, (t.CurrentPrice * ' + #selectedColumn + ') as TotalRevenuePerItem
FROM
dbo.SearchedUserItems t'
exec(#sql)
Perhaps pass the INDEX of the user's selection and use CHOOSE()
Let's assume:
Item Index
SevenDaySales 0
FourteenDaySales 1
TwentyOneDaySales 2
ThirtyDaySales 3
Then you can
SELECT COUNT(*) OVER () AS TotalRowsFound
,MIN(t.Title) AS Title
,t.ItemID
,choose(#Index+1,t.SevenDaySales,t.FourteenDaySales,t.TwentyOneDaySales,t.ThirtyDaySales) as SelectedColumnSales
,t.CurrentPrice
,(t.CurrentPrice * choose(#Index+1,t.SevenDaySales,t.FourteenDaySales,t.TwentyOneDaySales,t.ThirtyDaySales)) as TotalRevenuePerItem
FROM dbo.SearchedUserItems t
If you don't want to pass the index, rather then #Index+1 , you can #SelectedRange/7
Instead of a string concat you could try using direcly the login in query using a case when clause
SELECT
COUNT(*) OVER () AS TotalRowsFound,
MIN(t.Title) AS Title
, t.ItemID
, case when #SelectedRange=7 then t.SevenDaySales
when #SelectedRange=14 then t.FourteenDaySales
when #SelectedRange=21 then t.TwentyOneDaySales
when (#SelectedRange=30 then t.ThirtyDaySales end
as SelectedColumnSales
, t.CurrentPrice
, (t.CurrentPrice * t.SelectedColumnSales) as TotalRevenuePerItem
FROM
dbo.SearchedUserItems t
Wrap your query up in a derived table, then you can reference those columns outside it:
select dt.TotalRowsFound, dt.Title, ... ,
(dt.CurrentPrice * dt.SelectedColumnSales) as TotalRevenuePerItem
from
(
SELECT
COUNT(*) OVER () AS TotalRowsFound,
MIN(t.Title) AS Title
, t.ItemID
,' + #selectedColumn + ' as SelectedColumnSales ' +
', t.CurrentPrice
FROM
dbo.SearchedUserItems t
) dt

Add selected values from multi column into one column separated by ','

I want to select values from multiple columns into one column. I have 2 separate columns from which i want to get name,address,state,zip in following format in SQL Server 2008
Name (new line)
address,state,zip
Name (new line)
address,state,zip
Query:
select
name + char(13) + concat(address,',', state,',', zip)
from
tbl1
join
tbl2 on....
I am not able to get the desired output. I get concat is not a recognized built in function name.
You could use + operator and cast the zip field as varchar directly like this:
For example:
select 'Dara Singh' + char(13) + '1234 Main Street' + ',' + 'NY' + ','
+ cast(95825 as varchar(10))
This is how your query would look:
select name + char(13) + [address] + ',' + [state] + ',' + cast([zip] as varchar(10))
from tbl1 join tbl2 on....

Query display names

I have a 2 columns in a SQL Server table.
One is characters like 'Attn: firstname lastname', and the other column has a number associated with that person.
I can't figure out how to query them so the info comes out as:
Lastname, Firstname - number
If you are in SQL Server you can do this
Select Col1 + ' - ' + Col2
From dbo.{Table}
Where {Conditions}
If you mean you need to drop the "attn:" you can do something like this
Select substring(Col1, 5,len(Col1)-5) + ' - ' + Col2
From dbo.{Table}
Where {Conditions}
Instead of hardcoding the index of ':', you can do something like this
SELECT REPLACE(RIGHT(Col1, (LEN(Col1) - CHARINDEX(':', Col1)-1)),' ',', ') + ' - ' + Col2
To test this you can run the following
DECLARE #column1string AS VARCHAR(30), #column2number AS VARCHAR(10)
SET #column1string = 'Attn: Firstname Lastname'
SET #column2number = '12345678'
SELECT REPLACE(RIGHT(#column1string, (LEN(#column1string) - CHARINDEX(':', #column1string)-1)),' ',', ') + ' - ' + #column2number

SELECT statement issue - Joining of data of different fields in one cell of Gridview

I am using following SELECT statement for Gridview:
SelectCommand="SELECT ID, Date, Train, I_R, Dir_Ind, Detn, Rly, DiV, Loco, Shed, locoClass, loco_type,
(maj_sch_type + ','+ ' ' + maj_sch_place +',' +' '+ (CAST(maj_sch_dt as VARCHAR(11)) + ' '+'/'
+ ' ' + min_sch_type +',' + ' ' + min_sch_place + ',' + ' '+(CAST(min_sch_dt as VARCHAR (11))) )) as "major",
Equipt, I_R, reason
FROM PunctualityMain Order by Date ASC"
With the above, I am getting results in single cell from 6 (3 + 3) different fields of SQL data as
POH, KPA, Jan 2 2012 / IB, Shed, Apr 18 2012
Issue is this that whenever data in any group of 3 fields (before or after '/') is blank, Gridview cell is remain completely blank. If both group of fields having data than Gridview dispaly is OK as mentioned above. Can SELECT statement be modified for showing data in Gridview with any one group of fields are empty?
If you try to concatenate a null string with a non-null string, the result will be null.
Select NULL + 'test'
this will return NULL.
Also, I think your code didn't copy paste extremely well into your question, but you need to use the ISNULL() function. I think you can get the point. You'll probably have to clean up the code a bit for it to run. Just wrap every field that you are concatenating with ISNULL(MyField, '')
SELECT
ID,
Date,
Train,
I_R,
Dir_Ind,
Detn,
Rly,
DiV,
Loco,
Shed,
locoClass,
loco_type,
(isnull(maj_sch_type, '') + ', ' + isnull(maj_sch_place, '') +', '+ (isnull(CAST(maj_sch_dt as VARCHAR(11), '')) + ' / ' + isnull(min_sch_type, '') +', ' + isnull(min_sch_place, '') + ', '+ (isnull(CAST(min_sch_dt as VARCHAR (11)), '')) )) as "major",
Equipt,
I_R,
reason
FROM PunctualityMain
Order by Date ASC
Reference
IsNull