INSERT INTO SELECT with multiple CASE WHEN - sql-server

I am trying to insert into table using select from another table with multiple case scenarios. Each person has more than one value, which gives multiple rows in the jointable. I want to select col2 based on col1 from the jointable.
The outcome so far, is 3 line of same person, 1 of the 3 values in each row.
See result here
INSERT INTO #temp (Name, WageNo, Tiltraedelses_dato, Jubilaeum ,Sabbatical, Anciennitet)
SELECT
e.FirstName,
e.WageSystemKey,
e.[StartDate],
CASE WHEN v.EmployeeCustomColumnId = 2 THEN v.Value END,
CASE WHEN v.EmployeeCustomColumnId = 3 THEN v.Value END,
CASE WHEN v.EmployeeCustomColumnId = 1 THEN v.Value END
FROM Employees e
LEFT JOIN EmployeeCustomValue v on e.EmployeeId = v.EmployeeId
SELECT * FROM #temp

I think you need a group by with conditional aggregation, something like this
INSERT INTO #temp (Name, WageNo, Tiltraedelses_dato, Jubilaeum ,Sabbatical, Anciennitet)
SELECT
e.FirstName,
e.WageSystemKey,
e.[StartDate],
max(CASE WHEN v.EmployeeCustomColumnId = 2 THEN v.Value END),
max(CASE WHEN v.EmployeeCustomColumnId = 3 THEN v.Value END),
max(CASE WHEN v.EmployeeCustomColumnId = 1 THEN v.Value END)
FROM Employees e
LEFT JOIN EmployeeCustomValue v on e.EmployeeId = v.EmployeeId
group by e.FirstName,
e.WageSystemKey,
e.[StartDate]

Here are a couple of other ways to go about this.
INSERT INTO #temp (Name, WageNo, Tiltraedelses_dato, Jubilaeum ,Sabbatical, Anciennitet)
SELECT
e.FirstName,
e.WageSystemKey,
e.[StartDate],
v2.Value,
v3.Value,
v1.Value
FROM Employees e
LEFT JOIN EmployeeCustomValue v1 on e.EmployeeId = v1.EmployeeId and v1.EmployeeCustomColumnId = 1
LEFT JOIN EmployeeCustomValue v2 on e.EmployeeId = v2.EmployeeId and v2.EmployeeCustomColumnId = 2
LEFT JOIN EmployeeCustomValue v3 on e.EmployeeId = v3.EmployeeId and v3.EmployeeCustomColumnId = 3
Or
INSERT INTO #temp (Name, WageNo, Tiltraedelses_dato, Jubilaeum ,Sabbatical, Anciennitet)
SELECT FirstName, WageSystemKey, [StartDate],
MAX(Jubilaeum) AS Jubilaeum, MAX(Sabbatical) AS Sabbatical,
MAX(Anciennitet) AS Anciennitet
FROM (SELECT
e.FirstName,
e.WageSystemKey,
e.[StartDate],
CASE WHEN v.EmployeeCustomColumnId = 2 THEN v.Value END AS Jubilaeum,
CASE WHEN v.EmployeeCustomColumnId = 3 THEN v.Value END AS Sabbatical,
CASE WHEN v.EmployeeCustomColumnId = 1 THEN v.Value END AS Anciennitet
FROM Employees e
LEFT JOIN EmployeeCustomValue v on e.EmployeeId = v.EmployeeId) AA
GROUP BY FirstName, WageSystemKey, [StartDate]

Related

SQL Server : left join - check for right table column value is null

I have a query as follows:
select --this select should always give me 1 record
tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo,
CASE WHEN tbl3.Comments IS NOT NULL THEN 1 ELSE 0 END AS 'Required'
from
table1 tbl1
inner join
table2 tbl2 on tbl2.Id = tbl1.Id
left join -- This left join table gives me 5 records for one instance
(select
R.Id, C.Comments
from
tblC C
inner join
tblR R on R.Id = C.id) tbl3 on tbl3.Id = tbl2.Id
I want to write a CASE statement on the rows my left join is giving to check for null value as above and my final select query always return only 1 row. Is there a way to check if all five Comments Column values from my left join be checked for NULLs in the above query?
I would take a shortcut an use a COUNT() OVER PARTITION
CASE WHEN COUNT(*) OVER (PARTITION BY tbl3.Id) =0 THEN 0 ELSE 1 END AS 'Required'
You would have to DISTINCT your output above. Another option would be to GROUP BY and filter in the HAVING clause.
select --this select should always give me 1 record
tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo
From table1 tbl1
inner join table2 tbl2 on tbl2.Id = tbl1.Id
left join (-- This left join table gives me 5 records for one instance
SELECT R.Id,
C.Comments
FROM tblC C
INNER JOIN tblR R on R.Id = C.id
) tbl3 on tbl3.Id = tbl2.Id
GROUP BY
Id, Name, Address, relNo
HAVING
COUNT(*) = 5
Is this what you're looking for?
(CASE WHEN (select count(tbl3.id) FROM tbl3 WHERE tbl3.Comments IS NULL) then 1 else 0 end) as 'RequiredVal'
select --this select should always give me 1 record
tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo,
CASE WHEN tbl3.Comments IS NOT NULL THEN 1 ELSE 0 END AS 'Required'
, (CASE WHEN (select count(tbl3.id) FROM tbl3 WHERE tbl3.Comments IS NULL) then 1 else 0 end) as 'RequiredVal'
From table1 tbl1
inner join table2 tbl2 on tbl2.Id = tbl1.Id
left join (-- This left join table gives me 5 records for one instance
SELECT R.Id,
C.Comments
FROM tblC C
INNER JOIN tblR R on R.Id = C.id
) tbl3 on tbl3.Id = tbl2.Id

Count of insert and update by an employee

i/p
Id Name InsertBy UpdateBy
1 A 2 2
2 B 1 2
3 C 4 3
4 D 4 5
5 E 1 3
O/P(THE COUNT OF EMPLOYEE ID IN INSERT AND COUNT OF EMPID IN UPDATE)
Name InsertBy UpdateBy
A 2 0
B 1 2
C 0 2
D 2 0
E 0 1
It seems to you would require to do self join with separate query (Inserted, Updated) for safer.
SELECT
t.name, a.insertBy, b.updateBy
FROM table t
INNER JOIN
(
SELECT
t.id, count (t1.insertBy) insertBy
FROM table t
LEFT JOIN table t1 on t1.insertBy = t.id
GROUP BY t.id
)a on a.id = t.id
INNER JOIN
(
SELECT
t.id, count (t2.updateBy) updateBy
FROM table t
LEFT JOIN table t2 on t2.updateBy = t.id
GROUP BY t.id
)b on b.id = t.id
Let me edit with other approach which more efficient with separate join
select t1.name, sum(case when a.Name = 'InsertedBy' then 1 else 0 end) InsertBy,
sum(case when a.Name = 'UpdatedBy' then 1 else 0 end) UpdateBy
from table t
cross apply (
values (InsertBy, 'InsertedBy'), (UpdateBy, 'UpdatedBy')
)a(Types, Name)
LEFT JOIN table t1 on t1.Id = a.Types
group by t1.name
However, these will make use of index on (Id)

T-SQL Aggregate function subquery

I get the following error:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
With this code:
SELECT
loc.Location
,COUNT(CASE
WHEN hr.SAC in (SELECT [SAC] FROM dbo.[Titles] WHERE [title] = 'XYZ')
THEN 1
ELSE NULL
END) AS XYZ_Trainee_Count
,COUNT(CASE
WHEN hr.SAC in (SELECT [SAC] FROM dbo.[Titles] WHERE [title] = 'ABC')
THEN 1
ELSE NULL
END) AS ABC_Trainee_Count
FROM
dbo.n_HRODS hr INNER JOIN dbo.Locations loc
ON loc.LocationID = hr.LocationID
INNER JOIN dbo.EmpData dat
ON dat.EmpID = hr.EmpID
WHERE dat.Trainee = 1
GROUP BY loc.Location
dbo.[Titles] is a view that combines two columns from two other tables. I'm basically doing it this way because the programmer before me did something like this:
,COUNT(CASE
WHEN SAC in ( lists about 30 items)
THEN 1
ELSE NULL
END)
Obviously, I don't want to list 30 items in that case statement... and when those items change for whatever reason in 3 years, then who's going to remember to go back in this code and updated those items? Nobody...
Thanks in advance for your help.
You can do this with a couple of extra LEFT OUTER JOINs to that title table:
SELECT
loc.Location
,COUNT(CASE WHEN titles1.[SAC] IS NOT NULL THEN 1 ELSE NULL END) AS XYZ_Trainee_Count
,COUNT(CASE WHEN titles2.[SAC] IS NOT NULL THEN 1 ELSE NULL END) AS ABC_Trainee_Count
FROM
dbo.n_HRODS hr INNER JOIN dbo.Locations loc
ON loc.LocationID = hr.LocationID
INNER JOIN dbo.EmpData dat
ON dat.EmpID = hr.EmpID
LEFT OUTER JOIN dbo.[Titles] titles1
ON titles1.[title]='XYZ' AND
hr.SAC = titles1.[SAC]
LEFT OUTER JOIN dbo.[Titles] titles2
ON titles2.[title]='ABC' AND
hr.sac = titles2.[SAC]
WHERE dat.Trainee = 1
GROUP BY loc.Location
Alternatively, if you are really married to those subqueries in your SELECT statement because the actual query is a big nightmare and the thought of monkeying with the joins is enough to make you faint, then you can just remove the aggregation from this query and shove it all into a subquery before aggregation:
SELECT location, count(XYZ_Trainee) AS XYZ_Trainee_Count, count(ABC_Trainee) as ABC_Trainee
FROM
(
SELECT
loc.Location
,CASE
WHEN hr.SAC in (SELECT [SAC] FROM dbo.[Titles] WHERE [title] = 'XYZ')
THEN 1
ELSE NULL
END AS XYZ_Trainee
,CASE
WHEN hr.SAC in (SELECT [SAC] FROM dbo.[Titles] WHERE [title] = 'ABC')
THEN 1
ELSE NULL
END AS ABC_Trainee
FROM
dbo.n_HRODS hr INNER JOIN dbo.Locations loc
ON loc.LocationID = hr.LocationID
INNER JOIN dbo.EmpData dat
ON dat.EmpID = hr.EmpID
WHERE dat.Trainee = 1
) sub
GROUP BY location
I would aim for the first solution though since it's going to be easier to maintain and probably get a better execution path from your RDBMS and run quicker as a result. Although... that's just a guess.
Very similar to JNevill first answer. But if you join with title once, you can check and count for any number of title you want.
SELECT
loc.Location
,COUNT(CASE WHEN t.[title] = 'XYZ' THEN 1 END) AS XYZ_Trainee_Count
,COUNT(CASE WHEN t.[title] = 'ABC' THEN 1 END) AS ABC_Trainee_Count
FROM
dbo.[n_HRODS] hr
INNER JOIN dbo.[Locations] loc
ON loc.LocationID = hr.LocationID
INNER JOIN dbo.[EmpData] dat
ON dat.EmpID = hr.EmpID
INNER JOIN dbo.[Titles] t
ON hr.SAC = t.[SAC]
WHERE dat.Trainee = 1
GROUP BY loc.Location

How to use multiple values in between clause

Hi all is there any way that i can use multiple values in between clause as
column_name between 0 and 100 or 200 and 300 like this
Any help would be appreciated
here is my query SELECT CASE WHEN ISNUMERIC(value_text) = 1 THEN CAST(value_text AS INT) ELSE -1 END) between 0 and 100
i just want to append multiple values in between clause
This is full query
SELECT ROW_NUMBER() OVER
(
order by Vendor_PrimaryInfo.Vendor_ID asc
)AS RowNumber
, Unit_Table.Unit_title, Vendor_Base_Price.Base_Price, Vendor_Base_Price.showprice, Category_Table.Title, Vendor_Registration.Business_Name,
Vendor_PrimaryInfo.Street_Address, Vendor_PrimaryInfo.Locality, Vendor_PrimaryInfo.Nearest_Landmark, Vendor_PrimaryInfo.City, Vendor_PrimaryInfo.State,
Vendor_PrimaryInfo.Country, Vendor_PrimaryInfo.PostalCode, Vendor_PrimaryInfo.Latitude, Vendor_PrimaryInfo.Longitude, Vendor_PrimaryInfo.ImageUrl,
Vendor_PrimaryInfo.ContactNo, Vendor_PrimaryInfo.Email,Vendor_PrimaryInfo.Vendor_ID
FROM Unit_Table INNER JOIN
Vendor_Base_Price ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID INNER JOIN
Vendor_PrimaryInfo ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID INNER JOIN
Vendor_Registration ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID AND
Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID INNER JOIN
Category_Table ON Vendor_Registration.Category_ID = Category_Table.Category_ID
LEFT JOIN
Vendor_Value_Table ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID LEFT JOIN
Feature_Table ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID
where Vendor_Registration.Category_ID=5 and Vendor_PrimaryInfo.City='City'
AND(
value_text in('Dhol Wala$Shahnai Wala')
or
(SELECT CASE WHEN ISNUMERIC(value_text) = 1 THEN CAST(value_text AS INT) ELSE -1 END) between 0 and 100
)
You can do this using AND/OR logic
value_text NOT LIKE '%[^0-9]%' and
(
value_text between 0 and 100
Or
value_text between 101 and 200
)
If you don't want to repeat the column name then frame the range in table valued constructor and join with your table
SELECT Row_number()
OVER (
ORDER BY Vendor_PrimaryInfo.Vendor_ID ASC )AS RowNumber,
Unit_Table.Unit_title,
Vendor_Base_Price.Base_Price,
Vendor_Base_Price.showprice,
Category_Table.Title,
Vendor_Registration.Business_Name,
Vendor_PrimaryInfo.Street_Address,
Vendor_PrimaryInfo.Locality,
Vendor_PrimaryInfo.Nearest_Landmark,
Vendor_PrimaryInfo.City,
Vendor_PrimaryInfo.State,
Vendor_PrimaryInfo.Country,
Vendor_PrimaryInfo.PostalCode,
Vendor_PrimaryInfo.Latitude,
Vendor_PrimaryInfo.Longitude,
Vendor_PrimaryInfo.ImageUrl,
Vendor_PrimaryInfo.ContactNo,
Vendor_PrimaryInfo.Email,
Vendor_PrimaryInfo.Vendor_ID
FROM Unit_Table
INNER JOIN Vendor_Base_Price
ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID
INNER JOIN Vendor_PrimaryInfo
ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID
INNER JOIN Vendor_Registration
ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID
AND Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID
INNER JOIN Category_Table
ON Vendor_Registration.Category_ID = Category_Table.Category_ID
LEFT JOIN Vendor_Value_Table
ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID
LEFT JOIN Feature_Table
ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID
JOIN (VALUES (0, 100),
(101, 200),
(201, 300)) tc (st, ed)
ON Try_cast(value_text AS INT) BETWEEN st AND ed
OR Try_cast(value_text AS VARCHAR(100)) = 'Dhol Wala$Shahnai Wala'
WHERE Vendor_Registration.Category_ID = 5
AND Vendor_PrimaryInfo.City = 'City'
Note : You have stored two different information's in a single column which causes lot of pain when you want to extract the data like this. Consider changing your table structure

Top N percent Desc and Top M percent Asc

I am trying to get top 5 customertypes and show data for each 5 customer types, The balance (which can be any amount) I show them as "Other Customer Types". my issue is since the rows can be random and not perfectly divisible by a number then there can be repeated values in the top 5 showing up in the "Other" group which overstates the Total sales.
the Data is also being rendered in SSRS
My code using TOP PERCENT:
select final.[description], sum(final.YTDSales$) as YTDSales$
FROM(
select top 25 percent pytd2.[Description], sum(pytd2.YTDSales$) as YTDSales$
FROM(
-- ytd sales
select re.SIC_Desc as [description], sum((ol.NetAmt - ol.WhlOrdDiscAmt) / #exrt) AS YTDSales$
from dbo.order_line_invoice ol
INNER JOIN dbo.Vendor vd ON ol.Cono = vd.Cono AND vd.VendId = ol.VendId
inner join Product_Warehouse pw on ol.ProdId = pw.prodid and ol.WhseId = pw.whseid and ol.cono = pw.cono
inner join Customer c on ol.custId = c.CustId and ol.Cono = c.Cono
left join MDData.dbo.RetailEnvironment re on c.SIC = re.SIC
where ol.InvoiceDate BETWEEN #FStartDate AND #EndDate AND ol.Cono = 1 and ol.VendId IN(#Vendid) and ol.prodcatid NOT LIKE 'GP%'
group by re.SIC_Desc
)PYTD2
group by pytd2.[description]
order by sum(pytd2.YTDSales$) DESC
UNION ALL
select top 75 percent 'Other' as 'description', sum(pytd.YTDSales$) as YTDSales$
FROM(
-- ytd sales
select re.SIC_Desc as [description], sum((ol.NetAmt - ol.WhlOrdDiscAmt) / #exrt) AS YTDSales$
from dbo.order_line_invoice ol
INNER JOIN dbo.Vendor vd ON ol.Cono = vd.Cono AND vd.VendId = ol.VendId
inner join Product_Warehouse pw on ol.ProdId = pw.prodid and ol.WhseId = pw.whseid and ol.cono = pw.cono
inner join Customer c on ol.custId = c.CustId and ol.Cono = c.Cono
left join MDData.dbo.RetailEnvironment re on c.SIC = re.SIC
where ol.InvoiceDate BETWEEN #FStartDate AND #EndDate AND ol.Cono = 1 and ol.VendId IN(#Vendid) and ol.prodcatid NOT LIKE 'GP%'
group by re.SIC_Desc
)PYTD
group by Ppytd.[description]
order by sum(pytd.YTDSales$)
)final
group by final.[Description]
order by sum(final.YTDSales$) DESC
my results:
As you can see the Large Independent and Other has the same figure of $2280.60 in YTDQty since it is being repeated
I was picturing something like this:
with data as (
-- your base query here grouped and summarized by customer type
), rankedData as (
select *, row_number() over (order by YTDSales$ desc) as CustTypeRank
from data
)
select
case when CustTypeRank <= 5 then min("description") else 'Others' end as "description",
sum(YTDSales$) as YTDSales$
from rankedData
group by case when CustTypeRank <= 5 then CustTypeRank else 999 end
order by case when CustTypeRank <= 5 then CustTypeRank else 999 end
I actually used RANK instead which worked great :-
select 0 as rankytd, RANK() OVER(ORDER BY sum(ol.NetAmt - ol.WhlOrdDiscAmt) DESC) as rankpytd, re.sic, ol.VendId, vd.name, re.SIC_Desc As [description], 0 AS YTDQty, sum(ol.Quantity) AS PYTDQty
from dbo.order_line_invoice ol
INNER JOIN dbo.Vendor vd ON ol.Cono = vd.Cono AND vd.VendId = ol.VendId
inner join dbo.Product p on ol.Cono = p.Cono and ol.prodid = p.ProdId and p.ProdCatId in (#pcat)
inner join Product_Warehouse pw on ol.ProdId = pw.prodid and ol.WhseId = pw.whseid and ol.cono = pw.cono
inner join Customer c on ol.custId = c.CustId and ol.Cono = c.Cono
left join MDData.dbo.RetailEnvironment re on c.SIC = re.SIC
where ol.InvoiceDate BETWEEN DATEADD(YEAR, -1,#FStartDate) AND DATEADD(YEAR, -1, #EndDate) and ol.Cono = 1 and ol.VendId IN(#Vendid) and ol.prodcatid NOT LIKE 'GP%'
group by re.sic, ol.VendId, vd.Name, re.SIC_Desc

Resources