SQL query MAX functions - sql

I want to fetch data for a perticular product on basis of last user & respective last used time.Example
Host Product LastUserName LastUsedTime
1 X1 ABC 6/13/2014
1 X1 ABC 6/14/2014
1 X1 ABC 6/15/2014
1 X1 XYZ 6/14/2014
1 X1 XYZ 6/15/2014
1 X1 XYZ 6/16/2014
I have tried MAX function and find data as
Host Product LastUserName LastUsedTime
1 X1 ABC 6/15/2014
1 X1 XYZ 6/16/2014
But unable to get desired output which is
Host Product LastUserName LastUsedTime
1 X1 XYZ 6/16/2014
SQL:
select a.Netbios_Name0, b.DisplayName0, c.LastUserName0,
MAX(c.LastUsedTime0) as [Last Used Time]
from table1 a,table2 b,table3 c
where a.ItemKey = b.ResourceID
and a.ItemKey = c.ResourceID
group by a.Netbios_Name0, b.DisplayName0, c.LastUserName0
order by b.DisplayName0
Thanks for Help !!

For MSSQL :
select a.host, a.Product, a.LastUserName, a.LastUsedTime
from tablex a join
(
select Host, Product, max(LastUsedTime) as LastUsedTime
from tablex
group by Host, Product
) b on a.host = b.host and a.Product = b.Product and a.LastUsedTime = b.LastUsedTime

If you just want one row, don't use GROUP BY. Just order the results and use TOP 1 to get the first row (LIMIT 1 is for MySQL -- this is why you should always tell your RDBMS in questions).
select TOP 1 a.Netbios_Name0, b.DisplayName0, c.LastUserName0, c.LastUsedTime0
from table1 a,table2 b,table3 c
where a.ItemKey = b.ResourceID
and a.ItemKey = c.ResourceID
ORDER BY c.LastUsedTime0 DESC

Try this:
SELECT TOP 1 a.Netbios_Name0, b.DisplayName0, c.LastUserName0,
c.LastUsedTime0 as [Last Used Time]
FROM table1 a INNER JOIN
table2 b ON a.ItemKey = b.ResourceID INNER JOIN
table3 c ON a.ItemKey = c.ResourceID
WHERE c.LastUsedTime0 = (SELECT TOP 1 LastUsedTime0 FROM table3 WHERE ResourceID = c.ResourceID)

To get the row with the last date per product you first need to get that last date, then JOIN back to the others values
WITH L AS (
SELECT b.DisplayName0, MAX(c.LastUsedTime0) LastUsedTime0
FROM table2 b
INNER JOIN table3 c ON b.ResourceID = c.ResourceID
GROUP BY b.DisplayName0
)
SELECT a.Netbios_Name0, b.DisplayName0, c.LastUserName0
, c.LastUsedTime0 as [Last Used Time]
FROM table1 a
INNER JOIN table2 b ON a.ItemKey = b.ResourceID
INNER JOIN table3 c ON a.ItemKey = c.ResourceID
INNER JOIN L ON b.DisplayName0 = L.DisplayName0
AND c.LastUsedTime0 = L.LastUsedTime0
ORDER BY b.DisplayName0
if you need to separate also the host name you need to change the query to
WITH L AS (
SELECT a.Netbios_Name0, b.DisplayName0, MAX(c.LastUsedTime0) LastUsedTime0
FROM table1 a
INNER JOIN table2 b ON a.ItemKey = b.ResourceID
INNER JOIN table3 c ON a.ItemKey = c.ResourceID
GROUP BY a.Netbios_Name0, b.DisplayName0
)
SELECT a.Netbios_Name0, b.DisplayName0, c.LastUserName0
, c.LastUsedTime0 as [Last Used Time]
FROM table1 a
INNER JOIN table2 b ON a.ItemKey = b.ResourceID
INNER JOIN table3 c ON a.ItemKey = c.ResourceID
INNER JOIN L ON a.Netbios_Name0 = L.Netbios_Name0
AND b.DisplayName0 = L.DisplayName0
AND c.LastUsedTime0 = L.LastUsedTime0
ORDER BY b.DisplayName0
As a last advice please stop to write the JOIN definition in the WHERE clause, it's less readable and mix to different ideas

;with cte as
(
select max(lastusedtime) over (PARTITION by product) as mdate
,host,product,lastusername ,lastusedtime
from test1
)
select distinct host,product,lastusername ,lastusedtime from cte
where lastusedtime=mdate

SELECT Product_Usage.*
FROM Product_Usage
INNER JOIN (SELECT Product, max(LastUsedTime) LastUSedTime
FROM Product_Usage
GROUP BY Product) LastUsed
ON Product_Usage.Product = LastUsed.Product
AND Product_Usage.LastUsedTime = LastUsed.LastUsedTime

Try this:
SELECT TOP 1 * FROM table_name ORDER BY LastUsername DESC, LastUsedTime DESC

Related

SQL Server rows count return with inner join more than once in same table

I have this code
select
count(cat_item_tb.item_id),
count(t.item_id)
from
cat_tb
inner join
item_tb on cat_tb.cat_id = item_tb.cat_id
inner join
cat_item_tb on item_tb.item_id = cat_item_tb.item_id and t.ss = 0
inner join
cat_item_tb t on item_tb.item_id = t.item_id and t.ss = 1
All I need to return value without duplicate. In past code it must return 7 in every count but it's return 49 the two count() affected each other. I use distinct but it does not return the correct count, because there is (item_id) more than once in table
Thank you so much
Seems to me that you need to count distinct, to count the unique values
...
count(DISTINCT cat_item_tb.item_id)
...
The 2 counts in your query will be the same. That's simply because you INNER JOIN on those item_id's. So they will be identical by defenition.
If I understand correctly the task, you could use groub by to get desired results
select count(cat_item_tb.item_id), cat_item_tb.ss
from cat_tb
inner join item_tb on cat_tb.cat_id = item_tb.cat_id
inner join cat_item_tb on item_tb.item_id = cat_item_tb.item_id
where t.ss = 0 or t.ss = 1
group by cat_item_tb.ss
The query will return 2 rows with count values in first column.
More info about group by is here link
I believe you wanted to write something like:
select
count(c1.item_id),
count(c2.item_id)
from
cat_tb as a
inner join item_tb as b on ( a.cat_id = b.cat_id )
inner join cat_item_tb as c1 on ( b.item_id = c1.item_id ) and ( c1.ss = 0 )
inner join cat_item_tb as c2 on ( b.item_id = c2.item_id ) and ( c2.ss = 1 )
This won't work because of the inner joins. If the first join of c1 returns 3 rows and the second join of c2 returns 4 rows, you end up with count = 3*4
Try this:
;with cte1 as (
select
b.item_id,
'c1_count' = count( c1.item_id )
from
item_tb as b
left join cat_item_tb as c1 on ( b.item_id = c1.item_id ) and ( c1.ss = 0 )
group by
b.item_id
),
cte2 as (
select
b.item_id,
'c2_count' = count(c2.item_id)
from
item_tb as b
left join cat_item_tb as c2 on ( b.item_id = c2.item_id ) and ( c2.ss = 1 )
group by
b.item_id
)
select
a.item_id, a.c1_count, b.c2_count
from
cte1 as a
inner join cte2 as b on ( b.item_id = a.item_id )
For performance reasons you could replace the left join in ctes with inner join ONLY if you are sure that there are rows in cat_item_tb with item_id and all of them has the ss column set to 0 or 1.

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
...

Max Query Over Partition

I want to select max values related to query, but all results are coming. Any idea ?
QUERY
SELECT MAXRecID,MAXSetID,MAXRID,PreReifiedValue,ComplianceState
FROM v_CI_CurrentComplianceStatus as A
INNER JOIN v_CIRules as B
ON B.CI_ID = A.CI_ID
INNER JOIN v_R_System as C
ON C.ResourceID = A.ItemKey
INNER JOIN
( SELECT PreReifiedValue,setting_CI_ID,
MAX(RecordID) AS MAXRecID,
MAX(SettingID) AS MAXSetID,
MAX(RuleID) AS MAXRID
FROM CI_CurrentRuleDetail
GROUP BY PreReifiedValue,Setting_CI_ID,instancedata
) AS D
ON D.Setting_CI_ID = A.CI_ID
GROUP by MAXRecID,MAXSetID,MAXRID,PreReifiedValue,rulename,ComplianceState
Results
MAXRecID MAXSetID MAXRID PreReifiedValue ComplianceState
72057594038117564 16780566 16780622 10 2
72057594038117565 16780570 16780620 0 2
Try this query
SELECT
MAX(tmp.MAXRecID), MAX(tmp.MAXSetID), MAX(tmp.MAXRID), MAX(tmp.PreReifiedValue), MAX(tmp.ComplianceState)
FROM (
SELECT MAXRecID,MAXSetID,MAXRID,PreReifiedValue,ComplianceState
FROM v_CI_CurrentComplianceStatus as A
INNER JOIN v_CIRules as B
ON B.CI_ID = A.CI_ID
INNER JOIN v_R_System as C
ON C.ResourceID = A.ItemKey
INNER JOIN
( SELECT PreReifiedValue,setting_CI_ID,
MAX(RecordID) AS MAXRecID,
MAX(SettingID) AS MAXSetID,
MAX(RuleID) AS MAXRID
FROM CI_CurrentRuleDetail
GROUP BY PreReifiedValue,Setting_CI_ID,instancedata
) AS D
ON D.Setting_CI_ID = A.CI_ID
) AS tmp
GROUP by tmp.MAXRecID, tmp.MAXSetID, tmp.MAXRID, tmp.PreReifiedValue, tmp.rulename, tmp.ComplianceState

Select MAX within multiple inner join

I want to select max values related to query, but all results are coming. Any idea ?
QUERY
SELECT MAXRecID,MAXSetID,MAXRID,PreReifiedValue,ComplianceState
FROM v_CI_CurrentComplianceStatus as A
INNER JOIN v_CIRules as B
ON B.CI_ID = A.CI_ID
INNER JOIN v_R_System as C
ON C.ResourceID = A.ItemKey
INNER JOIN
(SELECT PreReifiedValue,setting_CI_ID,
MAX(RecordID) AS MAXRecID,
MAX(SettingID) AS MAXSetID,
MAX(RuleID) AS MAXRID
FROM CI_CurrentRuleDetail
GROUP BY PreReifiedValue,Setting_CI_ID,instancedata) AS D ON D.Setting_CI_ID = A.CI_ID
GROUP by MAXRecID,MAXSetID,MAXRID,PreReifiedValue,rulename,ComplianceState
Results
MAXRecID MAXSetID MAXRID PreReifiedValue ComplianceState
72057594038117564 16780566 16780622 10 2
72057594038117565 16780570 16780620 0 2

Select qry to using 2 databases

I have the below query:
SELECT
--a.DateEntered,
--a.InventoryId,
a.SKU, a.QtyOnHand,
b.Dateentered AS VDateEntered,
b.GoLive, b.DateOnSite, b.CostPrice,
--a.CurrentPrice,
m.name AS Status,
hrf.category, hrf.department, hrf.BrandedOB, hrf.Division,
hrf.Fascia,
(a.QtyOnHand * b.CostPrice) AS Cost_Value,
NULL AS Item_Quantity, NULL AS Item,
NULL AS Season, hrf.Company,
(a.QtyOnHand * b.CurrentPrice) AS Sellilng_Value,
b.merchandisingseason, b.CostPrice AS Costprice_RP,
b.CurrentPrice, b.InventoryID,
-- a.AverageUnitCost,
-- a.AverageUnitCost AS RP_Stk_AverageUnitCost,
-- a.CurrentPrice AS RP_Stk_Current_Price,
-- a.Statusid,
-- a.Quantity_Sign,
(a.QtyOnHand * b.CostPrice) AS Cost_Value_RP,
(a.QtyOnHand * b.AverageUnitCost) AS AWC_Value
-- a.StockReconciliationId,
-- a.AverageUnitCost,
FROM
[dbo].[FC03QTY] a
JOIN
dbo.inventory b ON a.SKU = b.SKU
LEFT JOIN
(------Hierarchy-------
SELECT
ih.InventoryId, hry.category, hry.department,
hry.BrandedOB, hry.Division, hry.Fascia, hry.Company
FROM
(SELECT
ihn.HierarchyNodeId, ihn.InventoryId
FROM bm.InventoryHierarchyNode IHN
GROUP BY ihn.HierarchyNodeId, ihn.InventoryId) IH
JOIN
(SELECT
g.categoryid, g.category, h.department, i.BrandedOB,
j.Division, K.Fascia, L.company
FROM
Category g (NOLOCK)
JOIN
Department H ON g.departmentid = h.departmentID
JOIN
BrandedOB I (NOLOCK) ON h.BrandedOBID = i.BrandedOBID
JOIN
Division j (NOLOCK) ON i.divisionid = j.divisionid
JOIN
Fascia k (NOLOCK) ON j.fasciaid = k.fasciaID
JOIN
company l (NOLOCK) ON k.companyid = l.companyid
GROUP BY
g.categoryid, g.category, h.department,
i.BrandedOB, j.Division, K.Fascia, L.company) HRY ON ih.HierarchyNodeId = hry.CategoryId
GROUP BY
ih.InventoryId, hry.category, hry.department,
hry.BrandedOB, hry.Division, hry.Fascia, hry.Company) HRF ON b.inventoryid = hrf.inventoryid
JOIN
inventorystatus m (NOLOCK) ON b.statusid = m.statusid
It is using 2 tables -
[dbo].[FC03QTY] a
and
dbo.inventory b
that are joined at the SKU level.
[dbo].[FC03QTY] is on the scratch database and dbo.inventory is on the reports database.
How can I get my query to use these tables if they are on 2 different db?
Any advice greatly received.
In sql server the syntaxis for tables is [database name].[schema name].[table name]
So you need something like this:
SELECT A.*, B.*
FROM
Database1.dbo.Table1 as A,
Database2.dbo.Table2 as B