How to make a schedule table query from SQL Server 2012? - c#

I need help to make a schedule table for employee from my table the main problem is the row not start from first row on every column so the row keep continue, see picture below:
we can see that the next column is null on the first row and continue from the last row. this is my query and table relations, you can see it below.
SELECT (SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Tuesday')) AS Selasa,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Wednesday')) AS Rabu,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Thursday')) AS Kamis,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Friday')) AS Jumat,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Sabtu')) AS Saturday,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Monday')) AS Minggu FROM JADWAL INNER JOIN
JADWALPEGAWAI ON JADWAL.IDJADWAL = JADWALPEGAWAI.IDJADWAL INNER JOIN
PEGAWAI ON JADWALPEGAWAI.IDPEGAWAI = PEGAWAI.IDPEGAWAI WHERE (JADWAL.SHIFT = 'I')

What seems to be causing your query not to behave as you expect, is that you have no GROUP BY clause in your query, which means that you get one row of output for each for (in this case) each row of the JadwalPegawai table.
At a minimum, adding GROUP BY Pegawai.NamaPegawai after your WHERE … clause should fix this, but I think that we can do even better:
Select Min(iif(j.Harikerja = 'Tuesday', p.NamaPegawai, Null)) As Selasa,
Min(iif(j.Harikerja = 'Wednesday', p.NamaPegawai, Null)) As Rabu,
…
From Jadwal As j
Join JadwalPegawai As jp On j.IdJadwal = jp.IdJadwal
Join Pegawai As p On jp.IdPegawai = p.IdPegawai
Where j.Shift = 'I'
Group By p.NamaPegawai;
This should be logically equivalent, but doesn't use subqueries. Hope I didn't make any spelling errors, I'm not too good at bahasa Indonesia...

Related

Finding records where a field value not in a list

Using Any to filter an entity list that does not contain members of a list of values causes N seperate queries, one for each of the list members.
eg.
List<ImportObject> retval = new List<ImportObject>();
r = (from a in olist
where !ctx.Boxes.Any(o => o.OrderNo == a.OrderNo)
select a).ToList();
Using query profiler, I see bunches of statements come across like this.
exec sp_executesql N'SELECT CASE
WHEN EXISTS (
SELECT 1
FROM [Box] AS [o]
WHERE [o].[OrderNo] = #__a_OrderNo_0)
THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END',N'#__a_OrderNo_0 nvarchar(50)',#__a_OrderNo_0=N'13NU004094'
Is there a better way to do this type of action?
Try doing a left-outer join on the boxes table:
var elemeWithouthBoxMatch =
(from elem in olist
join box in ctx.Boxes on box.OrderNo equals elem.OrderNo into matches
from sbox in matches.DefaultIfEmpty()
where sbox == null
select elem).ToList();

Subquery returned more than 1 value even when they don't return anything

I have a DB which is connected like this.
I am writing a WPF app to do simple insert/delete/update stuff to tables.
The problem goes like this:
I get an Advertisement object and try to insert it into the DB
public static int Insert(Advertisement Advertisement)
{
Database db = new Database();
db.Connect();
SqlCommand command = db.CreateCommand(SQL_INSERT);
PrepareCommand(command, Advertisement);
int ret = db.ExecuteNonQuery(command);
db.Close();
return ret;
}
The SQL_INSERT
public static String SQL_INSERT = "INSERT INTO \"Advertisement\" VALUES (#IDProduct," +
" #CampaignDescription, #CampaignStart, #CampaignEnd)";
IDAdvertisement is an IDENTITY.
I have a trigger set on Advertisement table INSERT
ALTER trigger [dbo].[AutomaticUserAdvertisementScoreCalculating]
ON [dbo].[Advertisement]
AFTER INSERT
AS
begin
begin transaction;
declare Users cursor for
Select "User".IDUser, Sum(Price), inserted.IDProduct from "User"
join Purchase as pu on "User".IDUser = pu.IDUser
join PurchaseProduct as pp on pu.IDPurchase = pp.IDPurchase
join Product as pr on pp.IDProduct = pr.IDProduct
join inserted on pr.IDProduct = inserted.IDProduct
where pr.ProductType = (select ProductType from Product
join Advertisement on Product.IDProduct = Advertisement.IDProduct
join inserted on Advertisement.IDProduct = inserted.IDProduct
where Advertisement.IDAdvertisement = inserted.IDAdvertisement)
GROUP BY "User".IDUser, inserted.IDProduct
HAVING Sum(Price) > 50;
declare #IDUser int;
declare #Price decimal;
declare #IDProduct int;
open Users;
fetch next from Users into #IDUser,#Price, #IDProduct;
while ##FETCH_STATUS=0
begin
insert into UserAdvertisementScore values(#IDUser, (select IDAdvertisement from Advertisement where IDProduct = #IDProduct), #Price);
fetch next from Users into #IDUser, #Price, #IDProduct;
end
close Users;
deallocate Users;
commit;
end
I don't know why, but depending on the IDProduct used, it might throw out this error.
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
Please tell me if you need any more information on this
I didn't feel that was really a duplicate. Sure the error was the same thing but the real issue in this question was that the trigger was majorly flawed. Pretty sure your entire trigger body could simplified to something pretty close to this. And you should NOT use transactions inside a trigger. There is already a transaction in progress and anything you do will cause the original transaction to get out of whack.
insert UserAdvertisementScore
( --or whatever the column names are. You should ALWAYS specify the columns for an insert
[User]
, Price
, IDProduct
)
Select u.IDUser
, Sum(Price)
, i.IDProduct
from [User] u
join Purchase as pu on u.IDUser = pu.IDUser
join PurchaseProduct as pp on pu.IDPurchase = pp.IDPurchase
join inserted i on pr.IDProduct = i.IDProduct
join Product as pr on pp.IDProduct = pr.IDProduct
GROUP BY u.IDUser
, i.IDProduct

LINQ query losing select when joining two queries

Just to set the context a little, I'm trying to use queries with mysql that use Late row lookup as shown in this article
https://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
but that's a story for another day but the idea is that you do a key search on the table and then join it onto the whole table to force a late row lookup and the problem is coming from my LINQ queries when joined together.
-- Key search query --
Calling Code
IQueryable<int> keySearch = _defaultQueryFactory.Load(ContextEnums.ClientContext, MapEntityToDTO(), whereStatement, clientID).OrderBy(orderBy).Skip(startRow).Take(pageSize).Select(x => x.ID);
Resulting Query
SELECT
`Extent1`.`Sys_InvoiceID`
FROM `tblinvoice` AS `Extent1`
WHERE 3 = `Extent1`.`FK_StatusID`
ORDER BY
`Extent1`.`InvoiceDate` ASC LIMIT 0,430
-- Full Table Search --
Calling Code
IQueryable<InvoiceDTOModel> tableSearch = _defaultQueryFactory.Load(ContextEnums.ClientContext, MapEntityToDTO(), null, clientID, true).OrderBy(orderBy);
Resulting Query
SELECT
`Extent1`.`ID`,
`Extent1`.`C1`,
`Extent1`.`C2`,
`Extent1`.`C3`,
`Extent1`.`C4`,
`Extent1`.`C5`,
`Extent1`.`C6`,
`Extent2`.`SID`,
`Extent2`.`S1,
`Extent2`.`S2`,
`Extent2`.`S3`,
`Extent3`.`EID`,
`Extent3`.`E1`,
`Extent4`.`DID`,
`Extent4`.`D1`,
`Extent4`.`D2`,
`Extent4`.`D3`,
`Extent4`.`D4`,
`Extent4`.`D5`
FROM `tbl1` AS `Extent1` INNER JOIN `tbl2` AS `Extent2` ON `Extent1`.`SID` = `Extent2`.`SID` INNER JOIN `tbl3` AS `Extent3` ON `Extent1`.`EID` = `Extent3`.`EID` LEFT OUTER JOIN `tbl4` AS `Extent4` ON `Extent1`.`ID` = `Extent4`.`DID`
ORDER BY
`Extent1`.`C4` ASC
-- Joining the Two Together --
Calling Code
keySearch.Join(tableSearch, key => key, table => table.ID, (key, table) => table).OrderBy(orderBy).ToListAsync();
Resulting Query
SELECT
`Join3`.`ID`,
`Join3`.`C1`,
`Join3`.`C1`,
`Join3`.`C1`,
`Join3`.`C1`,
`Join3`.`C1`,
`Join3`.`C1`,
`Join3`.`SID`,
`Join3`.`S1,
`Join3`.`S2`,
`Join3`.`S3`,
`Join3`.`EID`,
`Join3`.`E1`,
`Join3`.`DID`,
`Join3`.`D1`,
`Join3`.`D2`,
`Join3`.`D3`,
`Join3`.`D4`,
`Join3`.`D5`
FROM (
`Extent1`.`ID`,
`Extent1`.`C1`,
`Extent1`.`C2`,
`Extent1`.`C3`,
`Extent1`.`C4`,
`Extent1`.`C5`,
`Extent1`.`C6`
FROM `tblinvoice` AS `Extent1`
WHERE 3 = `Extent1`.`EID`
ORDER BY
`Extent1`.`C4` ASC LIMIT 0,430) AS `Limit1` INNER JOIN (SELECT
`Extent1`.`ID`,
`Extent1`.`C1`,
`Extent1`.`C2`,
`Extent1`.`C3`,
`Extent1`.`C4`,
`Extent1`.`C5`,
`Extent1`.`C6`,
`Extent2`.`SID`,
`Extent2`.`S1,
`Extent2`.`S2`,
`Extent2`.`S3`,
`Extent3`.`EID`,
`Extent3`.`E1`,
`Extent4`.`DID`,
`Extent4`.`D1`,
`Extent4`.`D2`,
`Extent4`.`D3`,
`Extent4`.`D4`,
`Extent4`.`D5`
FROM `tbl1` AS `Extent2` INNER JOIN `tbl2` AS `Extent3` ON `Extent2`.`SID` = `Extent3`.`SID` INNER JOIN `tblstatus` AS `Extent4` ON `Extent2`.`EID` = `Extent4`.`EID` LEFT OUTER JOIN `tbl3` AS `Extent5` ON `Extent2`.`ID` = `Extent5`.`DID`) AS `Join3` ON `Limit1`.`ID` = `Join3`.`ID`
ORDER BY
`Join3`.`C4` ASC
Basically the inner select brings back
FROM (
`Extent1`.`ID`,
`Extent1`.`C1`,
`Extent1`.`C2`,
`Extent1`.`C3`,
`Extent1`.`C4`,
`Extent1`.`C5`,
`Extent1`.`C6`
FROM `tblinvoice` AS `Extent1`
WHERE 3 = `Extent1`.`EID`
ORDER BY
`Extent1`.`C4` ASC LIMIT 0,430) AS `Limit1`
Instead of
FROM (
`Extent1`.`ID`,
FROM `tblinvoice` AS `Extent1`
WHERE 3 = `Extent1`.`EID`
ORDER BY
`Extent1`.`C4` ASC LIMIT 0,430) AS `Limit1`
--Note--
The actual query selects around 15 columns, I've just shortened it to this example, it has an effect on the search as the dataset grows in size and it shouldn't be selecting all of the fields but i suspect there's an error in my join.
Any help is much appreciated.

I want the last entries in my Microsoft SQL Server database but get duplication

My problem is that I want to start a database query which should give me the last (maxDate) entry of every Serial number.
I am working with a Microsoft SQL Server database.
The first picture shows all entries in the database:
After I have run the following code I get this output:
string aQuery = #" SELECT *
FROM (
SELECT SerialNumber, MAX(Date) as MaxDate
FROM eBox_Deploy
GROUP BY SerialNumber
) r
INNER JOIN eBox_Deploy t
ON t.SerialNumber = r.SerialNumber AND t.Date = r.MaxDate";
using (var db = new eBoxDataContext())
{
list.AddRange(db.ExecuteQuery<eBox_Deploy>(bQuery));
}
After picture:
Now my problem is that I have duplicates because they already exists in the database. Distinct doesn't work well because these all have different Id´s.
How can I get them away?
You could use windowed functions:
SELECT *
FROM (SELECT *,
rn = ROW_NUMBER() OVER(PARTITION BY [SerialNumber] ORDER BY [Date] DESC)
FROM eBox_Deploy) AS sub
WHERE rn = 1;
If your [Date] is not unique within SerialNumber group use RANK() to get ties.

Using Linq to Entities and havign a NOT IN clause

I have a SQL query that I am trying to convert to LINQ:
SELECT * FROM TABLE1
WHERE LICENSE_RTK NOT IN(
SELECT KEY_VALUE FROM TABLE2
WHERE REFERENCE_RTK = 'FOO')
So I wrote one query for inner query and then one query for the outer one and used Except:
var insideQuery = (from pkcr in this.Repository.Context.TABLE2 where pkcr.Reference_RTK == "FOO" select pkcr.Key_Value);
var outerQuery = (from pl in this.Repository.Context.TABLE1 select pl).Except(insideQuery);
But this is wrong. Cannot even compile it. What is the correct way of writing this?
You cannot compile second query, because Except should be used on Queryables of same type. But you are trying to apply it on Queryable<TABLE1> and Queryable<TypeOfTABLE2Key_Value>. Also I think you should use Contains here:
var keys = from pkcr in this.Repository.Context.TABLE2
where pkcr.Reference_RTK == "FOO"
select pkcr.Key_Value;
var query = from pl in this.Repository.Context.TABLE1
where !keys.Contains(pl.License_RTK)
select pl;
NOTE: Generated query will be NOT EXISTS instead of NOT IN, but that's what you want
SELECT * FROM FROM [dbo].[TABLE1] AS [Extent1]
WHERE NOT EXISTS
(SELECT 1 AS [C1]
FROM [dbo].[TABLE2] AS [Extent2]
WHERE ([Extent2].[Reference_RTK] == #p0) AND
([Extent2].[Key_Value] = [Extent1].[License_RTK]))

Categories

Resources