Sorry I am really a newbie into programming and I am trying to merge two different columns into one column using sql but if it is not possible can it be done using sql code in c#?
I have two tables Product1 and Product2, these tables both have CatID.
For Product1, the CatID contains
1
2
3
For Product2, the CatID contains
1
2
3
4
5
The results that I am getting using union is if they have both similar id it will be merge into one and using concat it will duplicate into like
1 1
2 2
3 3
4
5
But the results that I want is the 1 to 3 is from product1 and then the 4 to 8 from product2 like it will continue on counting with no duplicate:
1
2
3
4
5
6
7
8
Is this possible?
Try it like this:
SELECT CatID, ...OtherColumns...
FROM Product1
UNION SELECT CatID, ...OtherColumns...
FROM Product2
WHERE Product2.CatID NOT IN(SELECT CatID FROM Product1)
ORDER BY CatID
(test here: http://sqlfiddle.com/#!9/7887c):
CREATE TABLE T1(ID INT, txt VARCHAR(10));
INSERT INTO T1 SELECT 1, 'test A'
UNION SELECT 2, 'test B'
UNION SELECT 3, 'test C';
CREATE TABLE T2(ID INT, txt VARCHAR(10));
INSERT INTO T2 SELECT 1, 'test 1'
UNION SELECT 2, 'test 2'
UNION SELECT 3, 'test 3'
UNION SELECT 4, 'test 4'
UNION SELECT 5, 'test 5';
SELECT ID, txt
FROM T1
UNION SELECT ID, txt
FROM T2
WHERE T2.ID NOT IN(SELECT ID FROM T1)
ORDER BY ID
The result:
ID txt
1 test A
2 test B
3 test C
4 test 4
5 test 5
I am not sure what you want but with LINQ you can create a select. If you show us the SQL code it would be very helpful.
can you try this query, use union
select * from Product1
union
select * from Product2 NOT IN(SELECT CatID FROM Product1)
Related
Suppose I have a table with two columns:
TABLE A
-------
ProjectID NUMBER
STATUS VARCHAR2(6) // either 'CLOSED' or 'NEW'
There could be maximum two entries for a ProjectID with the two possible values of STATUS and the combination (ProjectID, STATUS) is unique.
I need to select only those ProjectID's that have status 'NEW'. Also, if for a projectID, there are two entries with different statuses (NEW and CLOSED), I don't want it in the output.
I tried using group by, then ordering the resultset descending (so as to get 'NEW' row for a project ID first) and then taking the first row in LINQ, similar to this:
var query = (from a in context.A.Where(o => o.STATUS == 'NEW')
group a by a.ProjectID into groups
select groups.OrderByDescending(o => o.ProjectID)
.ThenBy(o => o.STATUS)
.FirstOrDefault());
Butt it's resulting into an "APPLY" clouse in the query which is resulting into an error. Apparantly, Oracle 10g doesn't support it.
Any help is appreciated.
Something like this, perhaps?
SQL> with test (projectid, status) as
2 (select 1, 'new' from dual union -- should be returned
3 select 2, 'new' from dual union
4 select 2, 'closed' from dual union
5 select 3, 'closed' from dual union
6 select 4, 'new' from dual -- should be returned
7 )
8 select projectid
9 from test
10 group by projectid
11 having min(status) = max(status)
12 and min(status) = 'new';
PROJECTID
----------
1
4
SQL>
Proper tu use having count(distinct STATUS=1) :
create table tableA( ProjectID int, STATUS varchar2(10) );
insert all
into tableA values(1 ,'NEW')
into tableA values(1 ,'CHANGED')
into tableA values(2 ,'NEW')
into tableA values(3 ,'CHANGED')
select * from dual;
/
select * from
(
select ProjectID, max(STATUS) STATUS
from tableA
group by ProjectID
having count(distinct STATUS)=1
)
where STATUS = 'NEW';
I believe I have accomplished what you want, using a subquery in LINQ.
var query = (from a in context.A
where (from b in context.A
where b.ProjectID == a.ProjectID
select new { a.ProjectID, a.STATUS }).Distinct().Count() == 0
&& a.STATUS == "NEW"
select a.ProjectID).ToList();
Essentially, the outer query just makes sure that each a record has a NEW status, and the inner query makes sure that there are no two distinct records with the given ProjectID, because if there are, one is CLOSED. I avoided using a GROUP BY since you said your database does not support LINQ's way of doing it.
I hope I understood your problem correctly, and I hope this helps!
I have the table below, how would I select in SQL the last date of each month (from the list) in each categoryID?
I want to end up with something in the line off:
CategoryID | Current | Date
1 | 5 | 2016-09-30
1 | 3 | 2016-10-30
1 | 7 | 2016-11-30
1 | 2 | 2016-12-30
etc. as history builds up.
Image :
There are a few ways to approaches to do this, one of them could be using windowing function rownumber. Within the CTE (WITH) you get local order of the records within date(using covert to get rid of the time here)+CategoryID partition by datetime DESC (-> first is latest). You need to do this because you cannot use windowing functions in WHERE clause. Then, in the main query, you actually use this CTE as your source table and get only the latest record per partition.
WITH LocallyOrdered AS (
SELECT CategoryID,
StockCurrent,
ROW_NUMBER() OVER (
PARTITION BY CategoryID, CONVERT(date, RecordAdded)
ORDER BY RecordAdded DESC)
AS RowNumberOneIsLatest
FROM OriginalTable)
SELECT CategoryID, StockCurrent FROM LocallyOrdered WHERE RowNumberOneIsLatest = 1
Considering you're using MySQL, since you haven't mentioned.
Suppose this is your table named : 'Dummy'
cat_id current date
------ ------- --------
1 5 2016-09-30
1 3 2016-10-30
1 7 2016-11-30
1 2 2016-12-30
2 4 2016-10-31
2 6 2016-10-04
Executing this query :
select
o.cat_id,
(SELECT DISTINCT
a.date
from
Dummy a
where a.cat_id = o.cat_id
ORDER BY date DESC
LIMIT 1) as 'date'
from
Dummy o
group by o.cat_id ;
Gives you the Latest date of each category :
cat_id date
------ ------------
1 2016-12-30
2 2016-10-31
EDIT
This is supposed to work specifically for your table. Just replace "yourTable" with the table's actual name.
select
o.CategoryID,
o.StockCurrent
(SELECT DISTINCT
a.RecordAdded
from
yourTable a
where a.CategoryID = o.CategoryID
ORDER BY RecordAdded DESC
LIMIT 1) as 'RecordAdded'
from
yourTable o
group by o.CategoryID ;
EDIT 2 :
This Query returns the latest date of each month within a certain category. Hope this is what you want.
SELECT
o.CategoryID,
o.StockCurrent,
o.RecordAdded
FROM
`yourTable` o
WHERE o.RecordAdded IN
(SELECT
MAX(i.RecordAdded)
FROM
`yourTable` i
GROUP BY MONTH(i.RecordAdded))
GROUP BY o.CategoryID,
o.RecordAdded ;
Suppose the table contains the following sample data:
CategoryID StockCurrent RecordAdded
---------- ------------ -------------
1 5 2016-09-01
1 3 2016-09-02
1 7 2016-10-01
1 2 2016-10-02
2 4 2016-09-01
2 6 2016-09-02
2 66 2016-10-01
2 77 2016-10-02
Running this query returns the following result set :
CategoryID StockCurrent RecordAdded
---------- ------------ -------------
1 3 2016-09-02
1 2 2016-10-02
2 6 2016-09-02
2 77 2016-10-02
try this:
WITH Temp As
(
select CategoryId, [Current], RecordAdded,
Dense_Rank() over( partition by CategoryId order by RecordAdded desc) as CatergoryWiseRank
from tblCategory
)
select CategoryId, [Current], RecordAdded from Temp where CatergoryWiseRank=1
SELECT
CASE MONTH(date_field)
WHEN 1 THEN 'Enero'
WHEN 2 THEN 'Febrero'
WHEN 3 THEN 'Marzo'
WHEN 4 THEN 'Abril'
WHEN 5 THEN 'Mayo'
WHEN 6 THEN 'Junio'
WHEN 7 THEN 'Julio'
WHEN 8 THEN 'Agosto'
WHEN 9 THEN 'Septiembre'
WHEN 10 THEN 'Octubre'
WHEN 11 THEN 'Noviembre'
WHEN 12 THEN 'Diciembre'
END as Mes, COUNT(date_field) as cantidad FROM nacimientos
WHERE YEAR(date_field)='1991'
GROUP BY MONTH(date_field)asc
Result
I have 2 tables as below:
Parent child relationship (table 1):
SourceId SourceParentId
1 null
2 1
3 2
4 null
Items (Table 2):
Id SourceId
1 1
2 1
3 2
4 2
5 3
6 4
How to write a linq query that return me all items based on Source ID? If my input is SourceId = 1, i will get items 1,2,3,4 & 5. If my input for sourceId is 2, i will get 3 items: 3, 4 & 5. If my input for sourceID is 4, it will return me item 6. My parent child is N-level and items can appear at any level.
Help :(
Here try this
--Variable to hold input value
DECLARE #inputSourceID INT = 1;
--Recursive CTE that finds all children of input SourceID
WITH MyCTE
AS
(
SELECT SourceID,
SourceParentID
FROM table1
WHERE SourceID = #inputSourceID
UNION ALL
SELECT table1.SourceID,
table1.SourceParentID
FROM table1
INNER JOIN MyCTE
ON table1.SourceParentID = MyCTE.SourceID
)
--Join the CTE with the table2 to find all id
SELECT table2.ID
FROM MyCTE
INNER JOIN table2
ON MyCTE.SourceID = table2.SourceID
I have following table structures.
**Table_A**
A_Id(BigInt) Category_Ids(varchar(50))
1 1,2,3
2 2,3
**Table_B**
B_Id(BigInt) C_Id(Bigint) Name(varchar(50))
1 2 A
2 1 C
3 3 B
First Query:
In this query want to get the record where A_Id=1. I have executed following code.
Select [Category_Ids] from Table_A where A_Id=1
This returns the data table with single column and single row with values “1, 2, 3”
Assume that above query fills the data into the A_datatable. I get the string from following code.
String ids = A_datatable.column[0][“Category_Ids”];
Second Query:
Now, I have to fetch the values from Table_B where C_Id in (1, 2, 3). I have executed following code and passed the string value to following query.
Select * from Table_B where C_Id in (ids)
When I execute above query getting the error, failed to convert parameter value from a String to a Int64.
You can actually do it in a single query.
SELECT b.*
FROM Table_A a
INNER JOIN Table_B b
ON ',' + a.Category_IDs + ',' LIKE '%,' + CAST(C_ID AS VARCHAR(10)) + ',%'
WHERE a.A_ID = 1
Caveat: This query is an index-killer. You should have properly normalize your tables.
UPDATE 1
Suggested Schema Design,
Table_A
A_ID
Category_ID
Table_C
B_ID
C_ID
Name
Records
Table_A
A_ID Category_ID
1 1
1 2
1 3
2 4
2 5
Table_B
B_Id C_Id Name
1 2 A
2 1 C
3 3 B
You can use a string splitter function like the one described here http://www.sqlservercentral.com/articles/Tally+Table/72993/
scroll down to the 'CREATE FUNCTION' script and run it to create your function, then you can split the comma separate string for use in your 'where in' clause
select * from Table_B
where C_Id in (select item from dbo.DelimitedSplit8K(IDS,','))
I have 3 table how to get the value of 3rd table by using join in MySql
table1
RowID UserID RoleID
1 1 2
2 171 3
table2
RowID RoleID PermissionID
1 2 2
2 2 3
3 3 14
4 3 15
table3:
PermissionID PermissionName
2 Edit organisation
3 Delete organisation
14 Create group
15 Edit group
16 Delete group
Here I will know only the UserID, if suppose the UserID is 171, then I should get the roleid(3) from table1 and get PermissionID(14,15) from table 2 and then get the PermissionName(Create group, Edit group) from table 3 and I have to store it in a list. How can I do it. I am using c# and mysql. Thanks
SQL Query to select from DB:
SELECT p.PermissionID, p.PermissionName
FROM users u
INNER JOIN roles r ON r.RoleID = u.RoleID
INNER JOIN permissions p ON p.PermissionID = r.PermissionID
Next step: (But use ExecuteReader() instead of ExecuteNonQuery())
MSDN: ExecuteReader() example
Executing an SQL statement in C#?