I have following self-reference table
Name | Id |CategoryId
--------------------------------
Gruop1 | 1 |null
--------------------------------
Group2 | 2 | 1
--------------------------------
Group3 | 3 | 1
--------------------------------
Id=int AtuoNumber
CategoryId=int nullable
I need query that its result is like this (linq to sql or sql command)
Name | Id | CategoryId | CategoryName
---------------------------------------------------------
Gruop1 | 1 | null | null
---------------------------------------------------------
Group2 | 2 | 1 | Group1
---------------------------------------------------------
Group3 | 3 | 1 | Group1
---------------------------------------------------------
I tried this code but it didn't work properly
SELECT *
FROM Category e1
inner join Category e2
ON e1.Id = e2.CategoryId
Any idea?
SELECT e1.name,e1.id,e1.categoryid,e2.name as categoryname
FROM Category e1
left join Category e2
ON e2.id = e1.CategoryId
I am guessing that you are missing the null valued rows (where CategoryId is null). This is because in any RDBMS any comparison to NULL always returns false, even of you compare null to null.
To get what you want, I believe you need a UNION query, with the second part of the union selecting rows where CategoryId is null
SELECT e1.Name , e1.Id , e1.CategoryId, e2.Name as CategoryName
FROM Category AS e1 INNER JOIN Category AS e2 ON e1.id = e2.CategoryId
union
SELECT e1.Name , e1.Id , e1.CategoryId,null as CategoryName
FROM Category e1 where CategoryId is null
This will do the job for you.
declare #temp table
(
[Id] [int] IDENTITY(1,1),
[CategoryId] [int] NULL ,
Name varchar(20)
)
insert into #temp(CategoryId, Name)
values
(null,'Group1'),
(1,'Group2'),
(1,'Group3')
select t1.Name,t1.Id,t1.CategoryId,t2.Name
from #temp t1
left outer join #temp t2 on t1.CategoryId = t2.Id
Related
Is it possible to emulate the following MySQL query:
SELECT * FROM `tbl` ORDER BY `date` DESC LIMIT X, 10
(X is a parameter)
in MS Access?
While the Access/JET TOP keyword does not directly provide an OFFSET capability, we can use a clever combination of TOP, a subquery, and a "derived table" to obtain the same result.
Here is an example for getting the 10 rows starting from offset 20 in a Person table in ORDER BY Name and Id...
SELECT Person.*
FROM Person
WHERE Person.Id In
(
SELECT TOP 10 A.Id
FROM [
SELECT TOP 30 Person.Name, Person.Id
FROM Person
ORDER BY Person.Name, Person.Id
]. AS A
ORDER BY A.Name DESC, A.Id DESC
)
ORDER BY Person.Name, Person.Id;
Essentially, we query the top 30, reverse the order, query the top 10, and then select the rows from the table that match, sorting in forward order again. This should be fairly efficient, assuming the Id is the PRIMARY KEY, and there is an index on Name. It might be that a specific covering index on Name, Id (rather than one on just Name) would be needed for best performance, but I think that indexes implicitly cover the PRIMARY KEY.
Another way - Let say you want from 1000 to 1999 records in a table called table1 (of course if you have that many records) you can do something like this.
MSSQL
SELECT *
FROM table1 LIMIT 1000, 1999;
MS Access
SELECT TOP 1000 *
FROM table1
Where ID NOT IN (SELECT TOP 999 table1.ID FROM table1);
To break this down
SELECT TOP NumA *
FROM table1
Where ID NOT IN (SELECT TOP NumB table1.ID FROM table1);
UpperLimit = 1999
LowerLimit = 1000
NumA = UpperLimit - LowerLimit + 1
ex. 1000 = 1999 - 1000 + 1
NumB = LowerLimit -1
ex. 999 = 1000 - 1
A better query would be:
SELECT Users.*
FROM Users
WHERE Users.id In
(
SELECT TOP X A.id
FROM [
SELECT TOP Y Users.*
FROM Users
ORDER BY Users.reg_date DESC
]. AS A
ORDER BY A.reg_date ASC
)
ORDER BY Users.reg_date DESC
Where
if((totalrows - offset) < limit) then
X = (totalrows - offset)
else
X = limit
And:
Y = limit + offset
For example, if total_rows = 12, and we set the limit to 10 (show 10 users per page), and the offset is calculated as p * limit - (limit) where p is the number of the current page, hence in the first page (p = 1) we will get: X = 12 and Y = 10, on the second X = 2 and Y = 20. The list of users is ordered by registration date (descending).
Simple and fastest solution.
myTable {ID*, Field2, Filed3...}
Assume your SortOrder contain primary KEY only
SELECT TOP PageItemsCount tb01.*
FROM myTable AS tb01
LEFT JOIN (
SELECT TOP OffsetValue ID FROM myTable ORDER BY ID ASC
) AS tb02
ON tb01.ID = tb02.ID
WHERE ISNULL(tb02.ID)
ORDER BY tb01.ID ASC
SortOrder based on other fields with duplicated values, in this case you must include your primary key in SortOrder as last one.
For exemple, myTable
+-------+--------+--------+
| ID | Field2 | Filed3 |
+-------+--------+--------+
| 1 | a1 | b |
| 2 | a | b2 |
| 3 | a1 | b2 |
| 4 | a1 | b |
+-------+--------+--------+
SELECT TOP 2 * From myTable ORDER BY FIELD2;
+-------+--------+--------+
| ID | Field2 | Filed3 |
+-------+--------+--------+
| 2 | a | b2 |
| 4 | a1 | b |
| 3 | a1 | b2 |
| 1 | a1 | b |
+-------+--------+--------+
SELECT TOP 2 * From myTable ORDER BY FIELD2, FIELD3;
+-------+--------+--------+
| ID | Field2 | Filed3 |
+-------+--------+--------+
| 2 | a | b2 |
| 4 | a1 | b |
| 1 | a1 | b |
+-------+--------+--------+
But if we add ID to sort order [AS LAST IN FIELDS LIST]
SELECT TOP 2 * From myTable ORDER BY FIELD2, ID;
+-------+--------+--------+
| ID | Field2 | Filed3 |
+-------+--------+--------+
| 2 | a | b2 |
| 1 | a1 | b |
+-------+--------+--------+
Final request
SELECT TOP PageItemsCount tb01.*
FROM myTable AS tb01
LEFT JOIN (
SELECT TOP OffsetValue ID FROM myTable ORDER BY Field2 ASC, ID
) AS tb02
ON tb01.ID = tb02.ID
WHERE ISNULL(tb02.ID)
ORDER BY tb01.Field2 ASC, tb01.ID
You can definitely get the the equivalent of "Limit" using the top keyword. See:
Access Database LIMIT keyword
No, JET SQL does not have a direct equivalent. As a workaround, you could add a WHERE clause that selects an ordered/id column between two values.
If possible, you can also use pass-through queries to an existing MySQL/other database.
While TOP in MS-Access can limit records returned, it does not take two parameters as with the MySQL LIMIT keyword (See this question).
I have an table with ID NUMBER(18) and I have a class with properties public Int64 ID { get; set; } to mapping ID form C# vs Oracle.
My table definition
But I have an error when I get max ID like this:
Run query
SELECT MAX(ID) ID FROM MYTABLE
The system throw an error:
"Object of type 'System.Decimal' cannot be converted to type 'System.Int64'."
But when I run query like this:
SELECT ID FROM(
SELECT ID FROM MYTABLE ORDER BY ID DESC
) WHERE ROWNUM =1
It OK.
I don't know why (1) throw error, and why (2) done?
What is the difference between datatype (1) and (2)?
Possible scenario 1:
I guess that you have NULL values in table (so your both queries are not equivalent):
SELECT MAX(ID) ID FROM T_00_RQMM -- aggregate func ignore NULLS
But:
SELECT ID FROM(SELECT ID FROM T_00_RQMM ORDER BY ID DESC) WHERE ROWNUM = 1;
-- NULL is the max value
DBFiddle Demo
Anyway you should try mapping:
using System.Numerics;
...
public BigInteger ID { get; set; }
EDIT:
Possible scenario 2:
It may be problem with data type (then use explicit CAST):
SELECT CAST(MAX(ID) AS NUMBER(18,0)) ID FROM T_00_RQMM
DBFiddle Demo 2
Full demo:
CREATE TABLE T_00_RQMM (ID NUMBER(18,0));
INSERT INTO T_00_RQMM VALUES(NULL);
INSERT INTO T_00_RQMM VALUES(100);
CREATE TABLE t1 AS SELECT MAX(ID) ID FROM T_00_RQMM;
CREATE TABLE t2 AS SELECT ID FROM(SELECT ID FROM T_00_RQMM ORDER BY ID DESC)
WHERE ROWNUM = 1;
CREATE TABLE t3 AS SELECT CAST(MAX(ID) AS NUMBER(18,0)) ID FROM T_00_RQMM;
SELECT TABLE_NAME, COLUMN_NAME, DATA_PRECISION, DATA_SCALE
FROM all_tab_cols
where table_name in ('T1', 'T2', 'T3')
ORDER BY Table_name;
Output:
+------------+-------------+----------------+------------+
| TABLE_NAME | COLUMN_NAME | DATA_PRECISION | DATA_SCALE |
+------------+-------------+----------------+------------+
| T1 | ID | null | null |
| T2 | ID | 18 | 0 |
| T3 | ID | 18 | 0 |
+------------+-------------+----------------+------------+
I want to get the Catalog of a selected supplier along with the last purchase price which is the column Costs in the CommandDetails table as shown bellow :
Product (idproduct, productName)
Command (idCommand, CommandCode, CommandDate, idSupplier)
CommandDetails(idCommandDetails, idProduct, Qty, idCommand, Costs)
Supplier (idSupplier, SupplierName, SupplierAddress)
SupplierCatalog (idSupplier, idProduct)
I tried the row_number() Over (Partition by ...) and other methods but i'm missing something, my brain said enough.
Desired Result :
--------------------------------------------------
| SupplierName| ProductName | CommandDate | Costs|
--------------------------------------------------
| SUP1 | P1 | 01/01/2018 | 3,06 |
| SUP1 | P6 | 01/01/2018 | 1,65 |
| SUP1 | P8 | 03/01/2018 | 5,20 |
| SUP1 | P9 | 05/01/2018 | 8,00 |
| SUP1 | P10 | 01/01/2018 | NULL |
--------------------------------------------------
Null in Costs for P10 when the product has never been ordered.
My last attempt :
SELECT
*
FROM
(SELECT
Sct.idsupplier,
SCt.idProduct,
SCD.PurchasePriceCmd Costs,
SCD.Qty,
P.ProCode,
P.ProName,
Row_number() OVER(PARTITION BY Sct.idProduct order by P.ProCode) rn
FROM SupplierCatalog SCt
LEFT JOIN CommandDetails SCD
ON SCD.idProduct = SCat.idProduct
LEFT JOIN Command a
ON a.idCommand = SCD.idCommand
LEFT OUTER JOIN StoreCommand b
ON a.idCommand = b.idCommand
INNER JOIN Product P
ON P.idProduct = SCt.idProduct) t
where Sct.idSupplier = 4 and rn = 1
You could also try this:
SELECT
s.supplierName,
p.productName,
latestCommandDetail.CommandDate,
latestCommandDetail.Costs
FROM Supplier s
INNER JOIN SupplierCatalog sc ON sc.idSupplier = s.idSupplier
INNER JOIN Product p ON p.idProduct = sc.idProduct
OUTER APPLY
(
SELECT TOP 1
c.CommandDate,
cd.Costs
FROM Command c
INNER JOIN CommandDetails cd ON cd.idCommand = c.idCommand
WHERE c.idSupplier = s.idSupplier AND cd.idProduct = p.idProduct
ORDER BY c.CommandDate DESC
) latestCommandDetail
WHERE s.idSupplier = 4
ORDER BY
s.supplierName,
p.productName
I don't have SQL Server going on this machine at the moment so you may need to tweak the syntax. The trick is just doing a link to a subquery that returns the top row sorted by the date descending.
I'm assuming the idSupplier for "SUP1" is 4 as per you example code above.
OUTER APPLY (the other optional join) will return nulls if no record is returned from the sub query. If you are only interested in products with prices use CROSS APPLY instead.
Also note that this query does not determine what to do if:
- there are two Commands for the same last date from the same supplier for the same product but with different Costs
- the same product is sold twice under the same Command but at different Costs
In both cases this can probably be handled by extending the sort order of the sub-query or by grouping/aggregating the sub-query.
Something like this ought to work:
;with cte as (
select a.idCommand, b.idProduct, row_number() over (partition by b.idProduct
order by a.CommandDate desc) as rn, a.CommandDate, b.Costs
from Command a
inner join CommandDetails b on a.idCommand = b.idCommand
)
select
c.SupplierName, e.productName, cte.CommandDate, cte.Costs
from Supplier c
left join SupplierCatalog d on c.idSupplier = d.idSupplier
left join Product e on d.idProduct = e.idproduct
left join cte on e.idProduct = cte.idproduct and cte.rn = 1
where c.idSupplier = #SupplierNumber;
You can probably replace the common table expression at the top with a subquery, or take some fields out of the CTE and join them in later.
I made this question a while back.
SQL Server making rows into columns
Basically, the person that answered explained very well what I needed to do. However, I encountered a problem
aID| status | group |
-----------------------
1 | acti | group1 |
2 | inac | group2 |
A3 | acti | group1 |
Second Table: This table is fixed. It has around 20 values and the IDs are all numbers
atID| traitname |
------------------
1 | trait1 |
2 | trait2 |
3 | trait3 |
Third Table: This table is used to identify the traits the assets in the first table have. The fields that have the same name as fields in the above tables are obviously linked.
tID| aID | atID | trait |
----------------------------------
1 | 1 | 1 | NAME |
2 | 1 | 2 | INFO |
3 | 2 | 3 | GOES |
4 | 2 | 1 | HERE |
Now, the user wants the program to output the data in the following format:
aID| status | group | trait1 | trait2 | trait 3
-------------------------------------------------
1 | acti | group1 | NAME | INFO | NULL
2 | inac | group2 | HERE | NULL | GOES
A3 | acti | group1 | NULL | NULL | NULL
Now, the problem here is that, as you can see, A3 has no trait. In the final view, I would want A3 to appear completely null in the traits. But it doesn't appear at all, even though it's there. Does anyone know how can I fix this?
Here is the query I am using:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(traitname)
from Table2
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT aid, status, [group],' + #cols + '
from
(
select t1.aid,
t1.status,
t1.[group],
t2.traitname,
t3.trait
from table1 t1
inner join table3 t3
on t1.aid = t3.aid
inner join table2 t2
on t3.atid = t2.atid
) x
pivot
(
max(trait)
for traitname in (' + #cols + ')
) p '
execute sp_executesql #query;
The problem is you are using an INNER JOIN on your tables. An INNER JOIN returns all rows that have matching data in both tables.
Since you want to return everything from Table1, you will alter your query to use a LEFT JOIN instead of the INNER JOIN:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(traitname)
from Table2
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT aid, status, [group],' + #cols + '
from
(
select t1.aid,
t1.status,
t1.[group],
t2.traitname,
t3.trait
from table1 t1
left join table3 t3
on t1.aid = t3.aid
left join table2 t2
on t3.atid = t2.atid
) x
pivot
(
max(trait)
for traitname in (' + #cols + ')
) p '
execute sp_executesql #query;
As a side note, it is difficult to tell what the data types on your join columns are. Your Table1.aid column appears to be a varchar because of the A3 value but your Table3.aid column looks to be an int. If your data types are not the same, then you will need to cast the data on the join similar to -- on t1.aid = cast(t3.aid as varchar(10))
I am using C# and trying to do union on multiple datatables in the code.
Table 1
ID | Value | Value2
-----------------
1 | Tom | Null
-----------------
2 | John | Null
-----------------
...
Table 2
ID | Value | Value2
-----------------
1 | Null | Susie
-----------------
2 | Null | Kim
-----------------
...
And, I want the result table would be something like
TableResult
ID | Value | Value2
-----------------
1 | Tom | Susie
-----------------
2 | John | Kim
-----------------
...
Is there a way I could this?
I'm not sure what datastructure you are using in C#, but you can do this right in your database:
SELECT COALESCE(Table1.ID, Table2.ID) AS ID
,COALESCE(Table1.Value, Table2.Value) AS Value
,COALESCE(Table1.Value2, Table2.Value2) AS Value2
FROM Table1
FULL OUTER JOIN Table2
ON Table1.ID = Table2.ID
I chose a FULL OUTER JOIN here so that items could be missing on EITHER side (I generally expect most people will use a FULL OUTER JOIN about once a year in their careers), as well as an arbitrary choice to always pick the value in Table1 if it existed first, so Table2 would not overwrite something in Table1.
So as an example of how the FOJ works:
Table 1
1,A,NULL
2,B,X
3,NULL,Y
4,D,Z
Table 2
1,NULL,P
2,NULL,Q
3,C,NULL
5,E,W
Output:
1,A,P
2,B,X
3,C,Y
4,D,Z
5,E,W
If they're already in DataTables, you could load them into another table:
DataTable unionTable = new DataTable();
unionTable.Load(table1.CreateDataReader());
unionTable.Load(table2.CreateDataReader());
I think the notion of doing it server side as previously mentioned is a lot better approach though...
Another way to do this in Linq
//Lets say you have two tables (fill the variables from dababase)
IQueryable tab1 = new List().AsQueryable();
IQueryable tab2 = new List().AsQueryable();
//You can create Result table this way
var resultTable = tab1.Select(t1 => new Table1 { t1.ID, t1.Value, tab2.Any(t2 => t2.ID == t1.ID) ? tab2.First(t2 => t2.ID == t1.ID).Value : null });