Top 1 Item from the List in SQL - sql

I have the following scenario
I am getting Output like this
Month Product Name Amount
Jan-2014 A-Prodcut 50
Jan-2014 B-Product 45
Jan-2014 C-Product 55
Feb-2014 A-Prodcut 60
Feb-2014 B-Product 48
Feb-2014 C-Product 80
I want Output like this :
Jan-2014 C-Product 55
Feb-2014 C-Product 80
I want top product from each month How to achieve this
Here is my query
;With cte as
(
SELECT #EndDate AS TheMonth, 0 as [Counter]
UNION ALL
SELECT DATEADD(mm,-[Counter] -1,#EndDate), Counter + 1 AS TheMonth
from cte
WHERE DATEADD(mm,-[Counter] -1,#EndDate) >= #StartDate
)
SELECT
left(DATENAME(MM,TheMonth),3) +'-'+ cast(year(TheMonth) as varchar) AS [Month-Year],
ISNULL(IM.product_name,'N/A') as 'Product Name',
isnull(sum((ism.selling_price * siim.qty) + (((tm.tax_amount*(ism.selling_price * siim.qty))/100))),0) AS Amount
FROM
cte
LEFT OUTER JOIN RS_Sell_Order_Master AS SM on MONTH(invoice_date) = MONTH(TheMonth)
AND YEAR(invoice_date) = YEAR(TheMonth)
AND sm.is_approved = 1
LEFT OUTER JOIN RS_Sells_Invoice_Info_Master AS SIIM ON SM.sell_order_no = SIIM.sell_order_no
LEFT OUTER JOIN RS_Inventory_Master AS IM ON SIIM.product_id = IM.product_id
LEFT OUTER JOIN RS_Tax_Master AS TM ON TM.tax_id = SIIM.tax_id
LEFT OUTER JOIN RS_Inventory_Selling_Master AS ISM ON ISM.selling_product_id = SIIM.selling_product_id
GROUP BY
IM.product_name,
TheMonth

Use Row_number() in the select query ie.
SELECT MONTH, PRODUCT_NAME, AMOUNT
FROM (
SELECT MONTH, PRODUCT_NAME, AMOUNT,
ROW_NUMBER ( )
OVER (PARTITION BY Month order by amount Desc) AS RANK
)
WHERE RANK = 1
Hope this helps..

Try this:
SELECT *
FROM
(
SELECT [Month-Year], [Product Name], Amount, ROW_NUMBER() OVER (Partition BY [Month-Year] ORDER BY Amount DESC) as rn
FROM
(
SELECT
left(DATENAME(MM,TheMonth),3) +'-'+ cast(year(TheMonth) as varchar) AS [Month-Year],
ISNULL(IM.product_name,'N/A') as 'Product Name',
isnull(sum((ism.selling_price * siim.qty) + (((tm.tax_amount*(ism.selling_price * siim.qty))/100))),0) AS Amount
FROM
cte
LEFT OUTER JOIN RS_Sell_Order_Master AS SM on MONTH(invoice_date) = MONTH(TheMonth)
AND YEAR(invoice_date) = YEAR(TheMonth)
AND sm.is_approved = 1
LEFT OUTER JOIN RS_Sells_Invoice_Info_Master AS SIIM ON SM.sell_order_no = SIIM.sell_order_no
LEFT OUTER JOIN RS_Inventory_Master AS IM ON SIIM.product_id = IM.product_id
LEFT OUTER JOIN RS_Tax_Master AS TM ON TM.tax_id = SIIM.tax_id
LEFT OUTER JOIN RS_Inventory_Selling_Master AS ISM ON ISM.selling_product_id = SIIM.selling_product_id
GROUP BY
IM.product_name,
TheMonth
) a
)b
WHERE rn = 1

Usually OUTER APPLY or CROSS APPLY is a way to go in theese situations.
So your SELECT would be like this:
;With cte as
(
SELECT #EndDate AS TheMonth, 0 as [Counter]
UNION ALL
SELECT DATEADD(mm,-[Counter] -1,#EndDate), Counter + 1 AS TheMonth
from cte
WHERE DATEADD(mm,-[Counter] -1,#EndDate) >= #StartDate
)
SELECT
left(DATENAME(MM,TheMonth),3) +'-'+ cast(year(TheMonth) as varchar) AS [Month-Year],
'Product Name', Amount
FROM
cte
OUTER APPLY ( SELECT TOP 1
ISNULL(IM.product_name,'N/A') as 'Product Name',
isnull(sum((ism.selling_price * siim.qty) +
(((tm.tax_amount*(ism.selling_price * siim.qty))/100))),0) AS Amount
FROM RS_Sell_Order_Master AS SM
LEFT OUTER JOIN RS_Sells_Invoice_Info_Master AS SIIM
ON SM.sell_order_no = SIIM.sell_order_no
LEFT OUTER JOIN RS_Inventory_Master AS IM
ON SIIM.product_id = IM.product_id
LEFT OUTER JOIN RS_Tax_Master AS TM
ON TM.tax_id = SIIM.tax_id
LEFT OUTER JOIN RS_Inventory_Selling_Master AS ISM
ON ISM.selling_product_id = SIIM.selling_product_id
WHERE MONTH(invoice_date) = MONTH(TheMonth) AND YEAR(invoice_date) = YEAR(TheMonth) AND sm.is_approved = 1
ORDER BY Amount DESC
) x
GROUP BY
'Product Name',
TheMonth

Related

Select all records between two dates but one record on same day depending on plate

I have select query :
select
f.FirmaID,f.FirmaAdi,t.BelgeID,t.BelgeTuru,t.Tarih,t2.Plaka,t2.SasiNo,t4.AracMarka,t4.AracTip,case when x.Miktar=1 then 4 else x.miktar end as LastikAdet,
t3.CariKodu,t3.CariAdi,t3.CariGsm1,t3.CariGsm2,t3.CariTel1,t3.CariTel2,t3.CariAdres
from alsatr t WITH (NOLOCK)
left join Firma f WITH (NOLOCK) on f.FirmaID = t.AlsatrFirmaID
left join AracBilgi t2 WITH (NOLOCK) on t2.AracBilgiUID = t.AsAracBilgiUID and t2.AracBilgiID= t.AracBilgi
left join Cari t3 WITH (NOLOCK) on t.AsCariUID= t3.CariUID
left join Araclar t4 WITH (NOLOCK) on t4.AracID= t2.AB_AracID
outer apply
(select COUNT(1) soktak,Miktar FROM alsatD d WITH (NOLOCK)
where
d.AlsatDUID = t.AlsatrUID and d.AsStokKodu='LA-0001' group by Miktar) x
where
isnull(t3.FiloID,0) > 0
and t.Tarih between '04.30.2020' and '04.31.2020'
and t.BelgeTuru=55
and x.soktak > 0
and f.FirmaID not in (1,2,103,106,109,114)
order by t.Tarih desc, f.FirmaID desc, t.BelgeID desc
So I want to select all records between two days but I want to select one,latest record (maybe depends on last BelgeID ) on same day with same plate (plaka).
Enclose your query inside a CTE and use ROW_NUMBER() window function:
WITH cte AS (
<your query here>
)
SELECT
t.FirmaID, t.FirmaAdi, t.BelgeID, t.BelgeTuru, t.Tarih, t.Plaka, t.SasiNo, t.AracMarka,
t.AracTip, t.LastikAdet, t.CariKodu, t.CariAdi, t.CariGsm1, t.CariGsm2, t.CariTel1,
t.CariTel2, t.CariAdres
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Tarih, Plaka ORDER BY BelgeID DESC) rn
FROM cte
) t
WHERE t.rn = 1

Avoid SQL Pivot returning duplicate rows

I have the following SQL script which returns duplciate values in PIVOT. How do I combine those duplicate records to one row.
Please check the below image for the results set.
SELECT *
FROM (SELECT X.stockcode,
X.description,
X.pack,
X.location,
X.lname,
X.qty,
Y.stockcode AS StockCode2,
y.periodname,
Y.months,
Y.saleqty
FROM (SELECT dbo.stock_items.stockcode,
dbo.stock_items.description,
dbo.stock_items.pack,
dbo.stock_loc_info.location,
dbo.stock_locations.lname,
dbo.stock_loc_info.qty
FROM dbo.stock_locations
INNER JOIN dbo.stock_loc_info
ON dbo.stock_locations.locno = dbo.stock_loc_info.location
LEFT OUTER JOIN dbo.stock_items
ON dbo.stock_loc_info.stockcode = dbo.stock_items.stockcode
WHERE ( dbo.stock_items.status = 's' )) AS X
LEFT OUTER JOIN (SELECT dbo.dr_invlines.stockcode,
( 12 + Datepart(month, Getdate()) - Datepart(month, dbo.dr_trans.transdate) ) % 12 + 1 AS Months,
Sum(dbo.dr_invlines.quantity) AS SaleQty,
dbo.period_status.periodname
FROM dbo.dr_trans
INNER JOIN dbo.period_status
ON dbo.dr_trans.period_seqno = dbo.period_status.seqno
LEFT OUTER JOIN dbo.stock_items AS STOCK_ITEMS_1
RIGHT OUTER JOIN dbo.dr_invlines
ON STOCK_ITEMS_1.stockcode = dbo.dr_invlines.stockcode
ON dbo.dr_trans.seqno = dbo.dr_invlines.hdr_seqno
WHERE ( STOCK_ITEMS_1.status = 'S' )
AND ( dbo.dr_trans.transtype IN ( 1, 2 ) )
AND ( dbo.dr_trans.transdate >= Dateadd(m, -6, Getdate()) )
GROUP BY dbo.dr_invlines.stockcode,
Datepart(month, dbo.dr_trans.transdate),
dbo.period_status.periodname) AS Y
ON X.stockcode = Y.stockcode) z
PIVOT (Sum(saleqty) FOR [months] IN ([1],[2],[3],[4],[5],[6])) AS pivoted
EDIT: I missed the root-cause of your issue being the inclusion of the periodname column causing the percieved duplication. I am leaving this in place as general solution showing CTE usage, because it could still be useful if you then want to do extra filtering/transformation of your pivot results
One way is to take the results of the pivot query and run it through a SELECT DISTINCT query.
An example of wrapping your pivot query as a CTE and using it to feed a SELECT DISTINCT below (please note: untested, but parses as valid in my SSMS)
WITH PivotResults_CTE (
stockcode,
description,
pack,
location,
lname,
qty,
StockCode2,
periodname,
months,
saleqty
)
AS (
SELECT *
FROM (
SELECT X.stockcode
,X.description
,X.pack
,X.location
,X.lname
,X.qty
,Y.stockcode AS StockCode2
,y.periodname
,Y.months
,Y.saleqty
FROM (
SELECT dbo.stock_items.stockcode
,dbo.stock_items.description
,dbo.stock_items.pack
,dbo.stock_loc_info.location
,dbo.stock_locations.lname
,dbo.stock_loc_info.qty
FROM dbo.stock_locations
INNER JOIN dbo.stock_loc_info ON dbo.stock_locations.locno = dbo.stock_loc_info.location
LEFT OUTER JOIN dbo.stock_items ON dbo.stock_loc_info.stockcode = dbo.stock_items.stockcode
WHERE (dbo.stock_items.STATUS = 's')
) AS X
LEFT OUTER JOIN (
SELECT dbo.dr_invlines.stockcode
,(12 + Datepart(month, Getdate()) - Datepart(month, dbo.dr_trans.transdate)) % 12 + 1 AS Months
,Sum(dbo.dr_invlines.quantity) AS SaleQty
,dbo.period_status.periodname
FROM dbo.dr_trans
INNER JOIN dbo.period_status ON dbo.dr_trans.period_seqno = dbo.period_status.seqno
LEFT OUTER JOIN dbo.stock_items AS STOCK_ITEMS_1
RIGHT OUTER JOIN dbo.dr_invlines ON STOCK_ITEMS_1.stockcode = dbo.dr_invlines.stockcode ON dbo.dr_trans.seqno = dbo.dr_invlines.hdr_seqno WHERE (STOCK_ITEMS_1.STATUS = 'S')
AND (
dbo.dr_trans.transtype IN (
1
,2
)
)
AND (dbo.dr_trans.transdate >= Dateadd(m, - 6, Getdate()))
GROUP BY dbo.dr_invlines.stockcode
,Datepart(month, dbo.dr_trans.transdate)
,dbo.period_status.periodname
) AS Y ON X.stockcode = Y.stockcode
) z
PIVOT(Sum(saleqty) FOR [months] IN (
[1]
,[2]
,[3]
,[4]
,[5]
,[6]
)) AS pivoted
)
SELECT DISTINCT *
FROM
PivotResults_CTE
;
Also note, your sql included in the above may look slightly different to your original but that is only because i ran it through a reformatter to ensure i understood the structure of it.
In other words, the basic CTE wrapper for your pivot query is:
WITH PivotResults_CTE (
Field1,
Field2,
...
)
AS (
YOUR_PIVOT_QUERY_HERE
)
SELECT DISTINCT *
FROM
PivotResults_CTE
;

Group BY Expression column

we're trying to make our table add together all values in column 2 (QtyComp - an expression column of qtyorder * totalqty basically), where they have the same ItemNo (column 1).
So, we currently get the below:
ItemNo QtyCom
7441 3
7441 1
7441 5
What we want is it to return this:
ItemNo QtyCom
7441 9
Our code is below; I've bolded the part that we need it to sum the results of:
SELECT TOP (100) PERCENT ItemSpecs_2.itemno,
workorderdetails.qtycomplete *
ItemSpecFullStruc_2.totalqtyperroot AS QtyComp
FROM dbo.workorderdetails AS WorkOrderDetails
INNER JOIN dbo.itemspecfullstruc AS ItemSpecFullStruc_2
ON ItemSpecFullStruc_2.rootitemspecid =
workorderdetails.itemspecid
INNER JOIN dbo.itemspecs AS ItemSpecs_2
ON ItemSpecs_2.itemspecid = ItemSpecFullStruc_2.childitemspecid
INNER JOIN dbo.workorder AS WorkOrder_1
ON WorkOrder_1.workorderid = workorderdetails.workorderid
LEFT OUTER JOIN dbo.tobescheduled_completed
ON WorkOrder_1.workorderid =
dbo.tobescheduled_completed.workorderid
WHERE ( workorderdetails.completed = 1 )
AND ( workorderdetails.compdate > Getdate() - 42 )
GROUP BY ItemSpecs_2.itemno,
workorderdetails.qtyordered,
ItemSpecFullStruc_2.totalqtyperroot,
workorderdetails.[lineno],
workorderdetails.qtycomplete,
workorderdetails.compdate,
workorderdetails.qtycomplete * ItemSpecFullStruc_2.totalqtyperroot
We would really appreciate some ideas!
Thanks,
Trish
Try this
SELECT TOP (100) PERCENT ItemSpecs_2.itemno,
sum(workorderdetails.qtycomplete *
ItemSpecFullStruc_2.totalqtyperroot) AS QtyComp
FROM dbo.workorderdetails AS WorkOrderDetails
INNER JOIN dbo.itemspecfullstruc AS ItemSpecFullStruc_2
ON ItemSpecFullStruc_2.rootitemspecid =
workorderdetails.itemspecid
INNER JOIN dbo.itemspecs AS ItemSpecs_2
ON ItemSpecs_2.itemspecid = ItemSpecFullStruc_2.childitemspecid
INNER JOIN dbo.workorder AS WorkOrder_1
ON WorkOrder_1.workorderid = workorderdetails.workorderid
LEFT OUTER JOIN dbo.tobescheduled_completed
ON WorkOrder_1.workorderid =
dbo.tobescheduled_completed.workorderid
WHERE ( workorderdetails.completed = 1 )
AND ( workorderdetails.compdate > Getdate() - 42 )
GROUP BY ItemSpecs_2.itemno,
workorderdetails.qtyordered,
ItemSpecFullStruc_2.totalqtyperroot,
workorderdetails.[lineno],
workorderdetails.qtycomplete,
workorderdetails.compdate
Once you will use top for select statement, you need to use order by. you can try the following query.
SELECT TOP(100) PERCENT A.itemno,SUM(QtyComp) FROM
(SELECT ItemSpecs_2.itemno,
(workorderdetails.qtycomplete *
ItemSpecFullStruc_2.totalqtyperroot) AS QtyComp
FROM dbo.workorderdetails AS WorkOrderDetails
INNER JOIN dbo.itemspecfullstruc AS ItemSpecFullStruc_2
ON ItemSpecFullStruc_2.rootitemspecid =
workorderdetails.itemspecid
INNER JOIN dbo.itemspecs AS ItemSpecs_2
ON ItemSpecs_2.itemspecid = ItemSpecFullStruc_2.childitemspecid
INNER JOIN dbo.workorder AS WorkOrder_1
ON WorkOrder_1.workorderid = workorderdetails.workorderid
LEFT OUTER JOIN dbo.tobescheduled_completed
ON WorkOrder_1.workorderid =
dbo.tobescheduled_completed.workorderid
WHERE ( workorderdetails.completed = 1 )
AND ( workorderdetails.compdate > Getdate() - 42 ) ) A
GROUP BY A.itemno
ORDER BY A.itemno
Thanks
SELECT SUM(QTYCOM) OVER (PARTITION BY ITEMNO)
FROM
...

Selecting top result of each category of product

Below query is pulling back the data below.
I am trying to only return one single result for each product number, with only the highest orddate, and it related order total (ordttl) and unit cost (ucost).
Ideas on implementing? Thanks for any responses.
SELECT
ordln.pnum as 'Product Number',
prod.name as 'Product Name',
ordhd.snum,
sup.name,
ordhd.ordttl,
ORDHD.onum,
ORDHD.orddate,
ordln.ucost
FROM
scmdb.dbo.cksprodm prod (NOLOCK)
INNER JOIN scmdb.dbo.cksordln ordln (NOLOCK) on prod.pnum = ordln.pnum
INNER JOIN scmdb.dbo.cksordhd ordhd (NOLOCK) on ordhd.onum = ordln.onum
LEFT JOIN scmdb.dbo.ckssuplr sup (NOLOCK) on ordhd.snum = coalesce(sup.snum,
sup.asnum)
WHERE ordhd.orddate BETWEEN
DATEADD(month,-6,dateadd(day,datediff(day,0,getdate()),0) + '06:00') AND
GETDATE() -- order date is between 6 months ago and today.
AND ordln.pnum NOT IN (SELECT distinct PNUM
FROM scmdb.dbo.cksquohd qhd
inner join scmdb.dbo.cksquoln qln on qhd.quote = qln.quote
where qhd.qedate > GETDATE()
)
You can use row_number to rank by date and get latest date's row:
SELECT *
FROM
(
SELECT
ordln.pnum as 'Product Number',
prod.name as 'Product Name',
ordhd.snum,
sup.name,
ordhd.ordttl,
ORDHD.onum,
ORDHD.orddate,
ordln.ucost,
row_number() over (partition by ordln.pnum order by ORDHD.orddate desc) as ranking
FROM
scmdb.dbo.cksprodm prod (NOLOCK)
INNER JOIN scmdb.dbo.cksordln ordln (NOLOCK) on prod.pnum = ordln.pnum
INNER JOIN scmdb.dbo.cksordhd ordhd (NOLOCK) on ordhd.onum = ordln.onum
LEFT JOIN scmdb.dbo.ckssuplr sup (NOLOCK) on ordhd.snum = coalesce(sup.snum,
sup.asnum)
WHERE ordhd.orddate BETWEEN
DATEADD(month,-6,dateadd(day,datediff(day,0,getdate()),0) + '06:00') AND
GETDATE() -- order date is between 6 months ago and today.
AND ordln.pnum NOT IN (SELECT distinct PNUM
FROM scmdb.dbo.cksquohd qhd
inner join scmdb.dbo.cksquoln qln on qhd.quote = qln.quote
where qhd.qedate > GETDATE()
)
) t
where ranking = 1

How to insert into one table from multiple table while using UNION

I have the following query which queries different table and uses the UNION operator to display a set of data:
-----TOTAL COUNT OF ACTIVE DEA----- DEA
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobjectinsta d inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectinsta
group by fk1665) n on d.objectid = n.newobjectid where attr1671 = 'DEA' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
-----TOTAL COUNT OF ACTIVE LICENSES----- LICENSE
UNION
select 'LICENSE' as 'TYPE', count(*) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobjectin t inner join (select fk1656, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectin
group by fk1656) c on t.objectid = c.newobjectid where cast(attr1660 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL INFECTION CERTIFICATIONS ACTIVE----- INFECTION
UNION
select 'INFECTION' as 'TYPE', count(*) 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobject z inner join (select fk1676, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobject
group by fk1676) h on z.objectid = h.newobjectid where cast(attr1680 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL COUNT OF ACTIVE CDS----- CDS
UNION
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobje k inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobje
group by fk1665) l on k.objectid = l.newobjectid where attr1671 = 'CDS' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
Which displays the following:
TYPE TOTAL
CDS 45
DEA 56
INFECTION 67
LICENSE 41
I would like to insert the data into a table that I can import as a DataSet in my SSRS report. How can I achieve it?
I tried doing the following:
-----TOTAL COUNT OF ACTIVE DEA----- DEA
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobjectinsta d inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectinsta
group by fk1665) n on d.objectid = n.newobjectid where attr1671 = 'DEA' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
-----TOTAL COUNT OF ACTIVE LICENSES----- LICENSE
UNION
select 'LICENSE' as 'TYPE', count(*) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobjectin t inner join (select fk1656, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectin
group by fk1656) c on t.objectid = c.newobjectid where cast(attr1660 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL INFECTION CERTIFICATIONS ACTIVE----- INFECTION
UNION
select 'INFECTION' as 'TYPE', count(*) 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobject z inner join (select fk1676, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobject
group by fk1676) h on z.objectid = h.newobjectid where cast(attr1680 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL COUNT OF ACTIVE CDS----- CDS
UNION
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobje k inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobje
group by fk1665) l on k.objectid = l.newobjectid where attr1671 = 'CDS' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
But that didn't work. Please help...
This is the error I get:
Msg 196, Level 15, State 1, Line 2
SELECT INTO must be the first query in a statement containing a UNION, INTERSECT or EXCEPT operator.
You can try wrapping the whole thing as a subselect:
select *
into <whatever>
from (<your query here>
) t;
Try this :
With Emp_CTE (Employee,Count)
AS
(
Select Firstname as Employee , Count(*) as Count from Employee
where FirstName like 'V%'
group by FirstName
union
Select Firstname as Employee , Count(*) as Count from Employee
where FirstName like 'M%'
group by FirstName
)
Select * into dbo.EmployeeCount from Emp_CTE;