Given the following table:
Length | Width | Color | ID
===========================
18 | 18 | blue | 1
---------------------------
12 | 12 | red | 1
---------------------------
I want to produce a single column/row:
SIZES
=================
18 x 18, 12 x 12,
I can do this in SQL as follows:
DECLARE #SIZES VARCHAR(8000)
SELECT #SIZES = COALESCE(#SIZES, '') + Convert(varchar(80), [Length]) + ' x ' +
Convert(varchar(80), [Width]) + ', '
FROM table
where ID = 1
GROUP BY [Length], [Width]
ORDER BY [Length], [Width]
SELECT SIZES = #SIZES
But I cannot figure out how to do this in LINQ.
The closest I got was:
from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select new {
SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
Convert.ToInt32(g.Key.Width) + ", ")
}
Which produces one column and two rows:
SIZES
========
18 x 18,
12 X 12,
The converts are unimportant to the problem. The columns are defined as floats though all are integers. The key is the COALESCE function I cannot figure out how to do that in LINQ.
Try ?? (null coalesce operator) like:
t.Length ?? 0
I don't think LINQ to SQL supports this T-SQL trick. The COALESCE isn't really the issue (as Mehrdad points out the equivalent in C# is ??) -- it's the fact that SQL Server aggregates each result via string concatenation into the variable #SIZES. AFAIK LINQ to SQL can't construct this type of query.
This will yield your desired result, but the string concatenation is performed on your side, not on the SQL server side. That probably doesn't matter.
var query =
from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select new {
SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
Convert.ToInt32(g.Key.Width) + ", ")
};
var result = string.Join(string.Empty, query.Select(r => r.SIZES).ToArray());
I would just return the int sizes from SQL and do the string building client-side:
var query =
from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select g.Key;
var sizeStrings = from s in query.AsEnumerable()
select string.Format("{0} x {1}", s.Length, s.Width);
var result = string.Join(", ", sizeStrings.ToArray());
You could use the .Aggregate function, like so:
(from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select new {
SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
Convert.ToInt32(g.Key.Width) + ", ")
}).Aggregate((x,y) => x + y)
This should kick out a single string, like you want.
Aggregate just internally maintains the exact same variable you had defined in the SQL, just implicitly.
Related
I want do below query in Entity Framework
select
cast(p_min as varchar) + '' + cast(p_max as varchar)
from
user_behave_fact
where
beef_dairy_stat = 'True' and param_id = 2
group by
p_min,p_max
go
Since you have not mentioned a language, I am writing code in C#.
Try this:
using (var dbContext = new DatabaseContext())
{
var output = (
from fact in dbContext.user_behave_facts
where fact.beef_dairy_stat == "True" && fact.param_id == 2
group fact by new {fact.p_min, fact.p_max} in grp
select new
{
ColName = grp.Key.p_min.ToString() + " " + grp.Key.p_max.ToString()
}
).ToList();
}
.ToList() can be changed according to your expectations
I have the following dataframe which contains the AxiomaID.
x<-c(0123, 234, 2348, 345, 3454)
And trying to run the following SQL Query within R.
SQL6<-data.frame(sqlQuery(myConn, "SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID = x"))
How can I paste all the x values which contain the AxiomaID's into the SQL Query?
Try the following query:
SQL6<-data.frame(sqlQuery(myConn, paste("SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID IN (", paste(x, collapse = ", "), ")")))
Hope it helps!
You would try a function like
InsertListInQuery <- function(querySentence, InList) {
InValues <- ""
for (i in 1:length(InList)){
if (i < length(InList)) {
InValues <- paste(InValues,InList[[i]],",")}
else {
InValues <- paste(InValues,InList[[i]],sep = "")
}
}
LocOpenParenthesis <- gregexpr('[(]', querySentence)[[1]][[1]]
LocCloseParenthesis <- gregexpr('[)]', querySentence)[[1]][[1]]
if (LocCloseParenthesis-LocOpenParenthesis==1) {
querySentence<- gsub("[(]", paste("(",InValues,sep = ""), querySentence)
}
return (querySentence )
}
Function InsertListInQuery requires you to change your original query to one that use constraint IN () in WHERE clausule. What function does is to conform a string with vector elements separated by comma, and replace "(" string with the one composed. Finally, return a character variable.
Hence, you can define your vector of constraints list of elements, your query and call the function as shown:
x<-c(0123, 234, 2348, 345, 3454)
query <- "SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID IN ()"
finalQuery <- InsertListInQuery(query, x)
Value of finalQuery is:
finalQuery
[1] "SELECT top 10 [AxiomaDate] \n ,[RiskModelID]\n,[AxiomaID]\n,[Factor1]\nFROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]\nWhere AxiomaID IN ( 123 , 234 , 2348 , 345 ,3454)"
Note the line return with special character \n.
I hope it may help.
I have a servlet called DBChart mapped to url /db.the servlet outputs some data based on the sql query used here.
What I have:
At client end, I am making an ajax call like this:
$.ajax({
type : 'POST',
async: false,
url : 'http://localhost:8080/DBCHART/db',
success : function(data) {/*some code*/})
and At server end, a static query that says:
String sql ="select * from Employee"
What I want:
I want to be able to pass some parameters here like :
url: http://localhost:8080/DBCHART/db?Name = 'xyz'?Age = 21
and at server end, the query in this case should become:
select * from Employee where Name ='xyz' and Age = 21
i.e only if those parameters were supllied otherwise it should stay
select * from Employee
Can I please get some direction to create dynamic sql for this efficiently?
let's say in this case you're using varName as 'xyz' and varAge as 21
-- -- Name = 'xyz'?Age = 21
you can use some logic like this (point to ponder: WHERE 1 = 1 )
string sqlQuery = " select * from Employee where 1 = 1 ";
if(null != varName && !varName.isEmpty())){
// add criteria for Name
sqlQuery += " AND Name = '"+ varName + "'"; // TODO: use parametrized query
}
if(null != varAge && varAge > 0){
// add criteria for Age
sqlQuery += " AND Age = "+ varAge ; // TODO: use parametrized query
}
I was wondering if it is possible to combine column values based upon a condition. Let me explain...
Let say my data looks like this
Id name offset
1 Jan 100
2 Janssen 104
3 Klaas 150
4 Jan 160
5 Janssen 164
An my output should be this
Id fullname offsets
1 Jan Janssen [ 100, 160 ]
I would like to combine the name values from two rows where the offset of the two rows are no more apart then 1 character.
My question is if this type of data manipulation is possible with and if it is could someone share some code and explaination?
Please be gentle but this little piece of code return some what what I want...
ArrayList<String> persons = new ArrayList<String>();
// write your code here
String _previous = "";
//Sample output form entities.txt
//USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Berkowitz,PERSON,9,10660
//USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Marottoli,PERSON,9,10685
File file = new File("entities.txt");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if(_previous == "" || _previous == null)
_previous = scanner.nextLine();
String _current = scanner.nextLine();
//Compare the lines, if there offset is = 1
int x = Integer.parseInt(_previous.split(",")[3]) + Integer.parseInt(_previous.split(",")[4]);
int y = Integer.parseInt(_current.split(",")[4]);
if(y-x == 1){
persons.add(_previous.split(",")[1] + " " + _current.split(",")[1]);
if(scanner.hasNextLine()){
_current = scanner.nextLine();
}
}else{
persons.add(_previous.split(",")[1]);
}
_previous = _current;
}
} catch (Exception e) {
e.printStackTrace();
}
for(String person : persons){
System.out.println(person);
}
Working of this piece sample data
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Richard,PERSON,7,2732
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Marottoli,PERSON,9,2740
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Marottoli,PERSON,9,2756
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Marottoli,PERSON,9,3093
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Marottoli,PERSON,9,3195
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Berkowitz,PERSON,9,3220
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Berkowitz,PERSON,9,10660
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Marottoli,PERSON,9,10685
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Lea,PERSON,3,10858
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Lea,PERSON,3,11063
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Ken,PERSON,3,11186
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Marottoli,PERSON,9,11234
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Berkowitz,PERSON,9,17073
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Lea,PERSON,3,17095
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Stephanie,PERSON,9,17330
USER.A-GovDocs-f83c6ca3-9585-4c66-b9b0-f4c3bd57ccf4,Putt,PERSON,4,17340
Which produces this output
Richard Marottoli
Marottoli
Marottoli
Marottoli
Berkowitz
Berkowitz
Marottoli
Lea
Lea
Ken
Marottoli
Berkowitz
Lea
Stephanie Putt
Kind regards
Load the table using below create table
drop table if exists default.stack;
create external table default.stack
(junk string,
name string,
cat string,
len int,
off int
)
ROW FORMAT DELIMITED
FIELDS terminated by ','
STORED AS INPUTFORMAT
'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
location 'hdfs://nameservice1/....';
Use below query to get your desired output.
select max(name), off from (
select CASE when b.name is not null then
concat(b.name," ",a.name)
else
a.name
end as name
,Case WHEN b.off1 is not null
then b.off1
else a.off
end as off
from default.stack a
left outer join (select name
,len+off+ 1 as off
,off as off1
from default.stack) b
on a.off = b.off ) a
group by off
order by off;
I have tested this it generates your desired result.
I have the following data coming in to SSIS
Set Value
--- -------
1 One
1 Two
1 Three
2 Four
2 Five
2 Six
I want to transform it to read
Set ValueList
--- -------
1 One, Two, Three
2 Four, Five, Six
How do I do this in SSIS?
I used the Script Component to do the string concatenation across rows
string TagId = "-1";
string TagList = "";
bool IsFirstRow = true;
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
if (Row.TAGSId.ToString() == TagId)
{
TagList += Row.TAG + ",";
}
else
{
if (IsFirstRow)
{
Output0Buffer.AddRow();
IsFirstRow = false;
}
TagId = Row.TAGSId.ToString();
TagList = Row.TAG.ToString() + ",";
}
Output0Buffer.TagId = int.Parse(TagId);
Output0Buffer.TagList = TagList;
Output0Buffer.TagLength = TagList.Length;
//variable used in subsequent queries
this.Variables.TagList = TagList;
}
There is a pivot task in the data flow transformations. You could try it, but I'll warn you that we have been less than hapy with it's implementation.
Alternatively, you could use the dataflow to put the data into a staging table, and pivot using SQL or do the pivot in the SQL you use to create the incoming data source. If you want to do it in SQl code, this might help:
select 1 as Item
into #test
union select 2
union select 3
union select 4
union select 5
select STUFF((SELECT ', ' + cast(Item as nvarchar)
FROM #test
FOR XML PATH('')), 1, 1, '')