T-SQL Concatenating - sql-server

I need to concatenate the following statement in SQL.
I am joining 2 tables, the MEDINFO table and the IMMUNIZE table.
There should be one record for each of the shot code dates as long as it is not null or 01/01/1901.
The output must look like this:
"Admin-" + medinfo_field_31 + ", Manuf-" + medinfo_field_32 + ", Lot-" + medinfo_field_33 + ", Exp-" + medinfo_field_34 + ", Site-" + medifno_field_35 + ", Dose-" + medinfo_field_36
Here is the criteria for the SQL statement I must create:
IF immunize_shot_code = 'FLU',
then concatenate medinfo_field_12 and medinfo_field_19 thru medinfo_field_24
IF immunize_shot_code = 'MENI',
then concatenate medinof_field_11 and medinfo_field_25 thru medinof_field_30
IF immunize_shot_code = 'TETA',
then concatenate medinfo_field_13 thru medinfo_field_18 and medinfo_field_31 thru medinfo_field_36"
Thanks for any ideas.

This would look something like the followning:
SELECT
(CASE WHEN Immunize_shot_code='Flu'
THEN medinfo_field_12+', '+med_info_field_19+ ', '+med_info_field_20+', '+med_info_field_21+ ', '+med_info_field_22+', '+med_info_field_23+', 'med_info_field_24
WHEN immunize_shot_code='MENI'
THEN [CONCATINATE AS PER ABOVE]
.....
.....
END) as ImmuCode
FROM TABLE_1

Like some of them mentioned above, you could use CASE statement something like this:
select
case when i.immunize_shot_Code = 'FLU'
then concat(m.medinfo_field_12,',',m.medinfo_field_19,',',m.medinfo_field_24...)
when i.immunize_Shot_Code = 'MENI'
then concat(m.medinfo_field_11,',',m.medinfo_field_11)
when i.immunize_Shot_code = 'TETA'
then concat(m.medinfo_field_13,',',m.medinfo_field18,',')
end as concat_value
from medinfo m
join immunize i on m.id = i.medinfo_id --change this to match your join
where (shot_code_date is not null or shot_code_date <> '01-01-1901');

Related

Create a joined Key-Value in LinqToSql

I have a GridView binded to LinqToSql-DataSource. The DataSource is Multiple-Join. I need unique Key-Values for the Grid. But all PrimaryKeys from the Tables could exist double or not because of left joins.
I have solved the problem in a pure sql-statement. There i create a ID for the TableRows by joining two PrimaryKeys an connecting with a "-". I need one of the IDs for later working with TableRows, the other could be null.
So I do in SQL-Statement:
select CAST(mitgliedschaft.id as varchar(MAX)) + '-' + CAST(ISNULL(funktion.id, '') as varchar(MAX)) as id from ...... inner join ...... etc
I need the CASTS for not producing Calculating with the "-" and the ISNULL-Function because the second ID could be Null.
Now I have to transfer this part of the scenario into Linq-Statement. I tried like this:
...
...
select new
{
...
id = mitgliedschaft.id.ToString() + "-" + (funktion.id == null ? 0 : funktion.id).ToString()
...
});
But didn't get it running in that way. Can someone help me concatenating an ID with "-" and an ID that can be NULL? If it is NULL it should be an empty String or Null-Digit or whatever.
got it now:
select new
{
id = (mitgliedschaft.id.ToString() + "-") + (funktion.id.ToString() ?? "0")
}

SQL how to check prefix in cell with two prefixes

I am learning SQL and I have a table where there are certain cells with two prefixes like this :
example1(cell) : R:8days; U:5$;
example2(cell) : R:8days;
example3(cell) : U:5$;
I want to check for that U:5$ after the first prefix, as I know how to check for prefix R:8days;. So I need to check for U:5$ and then make a new column in table.
My code looks like this:
;with cte as (
select
Employer, AmountPayd, AmountPayd as Payd
from data
where TipeOfTransaction like 'Offline Prepaid%' AND Note like '%R:8%' **HERE I WANT TO CHECK FOR PREFIX NR2. 'U:5$' AND MAKE NEW COLUMN FOR WHICH EMPLOYER HAS U:5$ NOTE.**
)
select
Employer,
[4.00] = ISNULL([4.00],0)
,[5.00] = ISNULL([5.00],0)
,[9.00] = ISNULL([9.00],0)
,[10.00] = ISNULL([10.00],0)
,[15.00] = ISNULL([15.00],0)
,[Sum] =ISNULL([4.00],0) + ISNULL([5.00],0) + ISNULL([9.00],0) + ISNULL([10.00],0) + ISNULL([15.00],0)
from cte
pivot (
sum(AmountPayd) for Payd in ([4.00],[5.00],[9.00], [10.00], [15.00], [20.00]))pvt;
This?
select
Employer, AmountPayd, AmountPayd as Payd,
CASE WHEN Note like '%R:8%;%U:5$%' THEN 'U:5' END U5Note
from data
where TipeOfTransaction like 'Offline Prepaid%' AND Note like '%R:8%'
(I've corrected some mistakes in column names and refactored the query.)
I believe, you are looking for something like this:
WITH CTE AS (
SELECT
Employer,
AmountPaid,
Paid
FROM Data
LEFT JOIN (VALUES (4, 5, 9, 10, 15, 20)) V(Paid)
ON Note LIKE '%U:' + CAST(Paid AS VARCHAR(10)) + '$;%'
WHERE TypeOfTransaction LIKE 'Offline Prepaid%'
AND Note LIKE '%R:8%'
)
SELECT
Employer,
ISNULL([4.00], 0) AS [4.00],
ISNULL([5.00], 0) AS [5.00],
ISNULL([9.00], 0) AS [9.00],
ISNULL([10.00], 0) AS [10.00],
ISNULL([15.00], 0) AS [15.00],
ISNULL([4.00] + [5.00] + [9.00] + [10.00] + [15.00], 0) AS Sum
FROM CTE
PIVOT( SUM(AmountPaid)
FOR Paid IN ([4.00],[5.00],[9.00], [10.00], [15.00], [20.00])) PVT;

Can Any one help me to convert this sql query into linq

I need to convert this SQL Query to Link :
"Select * FROM [Register]
where RegisterId IN (SELECT MyId
FROM Friends
WHERE FriendId='" + Session["CurrentProfileId"] + "'
AND Status=1
UNION
SELECT FriendId
FROM Friends
WHERE MyId='" + Session["CurrentProfileId"] + "'
AND Status=1) ";
It may be look like this??? but this is incorrect and having errors
(from u in db.Register
where RegisterId).Contains
(from f in db.Freinds
where f.MyId == Id && m.Status == 1
select new { m.MyId })
.Union(from m in db.Freinds
where f.FreindId == Id && m.Status == 1
select new { m.CreateDate } ));
You have a few problems with the linq above and here are a few:
In the query in the Union you select the CreateDate whereas in the top on you select the MyId. I assume you meant to select FreindId.
In these 2 queries you create an anonymous class instance with the field but then compare it to the RegisterId which is probably a guid/string/int - but for sure not of the type you just created.
You are using the Contains method wrong. Linq syntax can be similar to sql but it is not the same. Check here for Contains
The correct Linq way of doing it is:
var idsCollection = ((from f in db.Freinds
where f.StatusId == 1 && f.MyId == Id
select f.MyId)
.Union(from m in db.Friends
where m.StatusId == 1 && f.FreindId == Id
select m.FriendId)).ToList();
var result = (from u in db.Register
where idsCollection.Contains(u.RegisterId)
select u).ToList();
Notice that the .ToList() is not a must and is here just to ease in debugging. For more information about this .ToList() and Linq in general check MSDN

Comparison of multiselect picklist with a field in text format in apex

I have an object with number of records in this format with Name in Text format -
Id Name
1 A,B,C
2 A,B
3 A
4 B
5 A,C
6 A,D
I have a multi-select picklist with values as:
A
B
C
D
So if I select B and C in my picklist, then I must have the records from the table in which name consists of B or C or (B and C) i.e. in this case, it should show 4 records:
1 A,B,C
2 A,B
4 B
5 A,C
I am using SQL query with IN and INCLUDES keyword but I am unable to achieve this functionality.
This depends on how many options you have for using soql. One way I can see it is:
Object__c myObject = new Object__c();
object.Name = 'A,B,D';
object.Multi_Select_Name__c = 'A;E';
insert object;
String query = 'select Id from Object__c';
//now we want to do a multi picklist, which is a String separated by ';'
List<String> nameSelections = object.Multi_Select_Name__c.split(';');
if(nameSelections.size() > 0) {
query += ' where ';
for(Integer i = 0; i < nameSelections.size(); i++) {
nameSelections[i] = 'Name like \'%' + nameSelections[i] + '%\'';
}
query += String.join(nameSelections, ' or ');
}
List<Object__c> objects = (List<Object__c)database.query(query);
This will create a query like:
'select Id from Object__c where Name like '%A%' or Name like '%E%'
Selecting all Object__c's where Name contains either A or E, generated from your multiselect.
Syntax errors may apply, I just wrote this real quick :) Ill double check myself.
EDIT:
This code works to build the query
String query = 'select Id from Object__c';
String multiSelect = 'A;E';
List<String> nameSelections = multiSelect.split(';');
if(nameSelections.size() > 0 ){
query += ' where ';
for(Integer i = 0; i < nameSelections.size(); i++) {
nameSelections[i] = 'Name like \'%' + nameSelections[i] + '%\'';
}
query += String.join(nameSelections, ' or ');
}
system.debug(LoggingLevel.INFO, query);

HIbernate + MSSQL query compatibility

I need to get the latest "version" of a Task object for a given objectUuid. The Task is identified by its objectUuid, taskName and createdTimestamp attributes.
I had the following HQL query:
select new list(te) from " + TaskEntity.class.getName() + " te
where
te.objectUuid = '" + domainObjectId + "' and
te.createdTimestamp = (
select max(te.createdTimestamp) from " + TaskEntity.class.getName() + " teSub
where teSub.objectUuid = te.objectUuid and teSub.taskName = te.taskName
)
which ran and produced the correct results on H2 (embedded) and MySQL.
However after installing this code in production to MS SQL Server I get the following error:
An aggregate may not appear in the WHERE clause unless it is in a
subquery contained in a HAVING clause or a select list, and the column
being aggregated is an outer reference.
I tried to rewrite the query but HQL doesn't seem to support subqueries properly. My latest attempt is something like:
select new list(te) from " + TaskEntity.class.getName() + " te
inner join (
select te2.objectUuid, te2.taskName, max(te2.createdTimestamp)
from " + TaskEntity.class.getName() + " te2
group by te2.objectUuid, te2.taskName
) teSub on
teSub.objectUuid = te.objectUuid and teSub.taskName = te.taskName
where
te.objectUuid = '" + domainObjectId + "'
but of course it fails at the "(" after the join statement.
Since this is a very frequent type of query I cannot believe there is no solution that works with HQL+MSSQL.
Uh-oh. Can this be a typo?
max(teSub.createdTimestamp)
instead of
max(te.createdTimestamp)
in the subquery.

Resources