Max Query Over Partition - sql

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

Related

Finding the count

I have the following SQL query and need to know the count of companyid as I can see repeating data. How do I find the count of it. Following is the query
SELECT a.companyId 'companyId'
, i.orgDebtType 'orgDebtType'
, d.ratingTypeName 'ratingTypeName'
, c.currentRatingSymbol 'currentRatingSymbol'
, c.ratingStatusIndicator 'ratingStatusIndicator'
, g.qualifierValue 'qualifierValue'
, c.ratingdate 'ratingDate'
, h.value 'outlook'
FROM ciqRatingEntity a
JOIN ciqcompany com
on com.companyId = a.companyId
JOIN ciqratingobjectdetail b ON a.entitySymbolValue = b.objectSymbolValue
JOIN ciqRatingData c ON b.ratingObjectKey = c.ratingObjectKey
JOIN ciqRatingType d ON b.ratingTypeId = d.ratingTypeId
JOIN ciqRatingOrgDebtType i ON i.orgDebtTypeId=b.orgDebtTypeId
JOIN ciqRatingEntityData red ON red.entitySymbolValue=a.entitySymbolValue
AND red.ratingDataItemId='1' ---CoName
LEFT JOIN ciqRatingDataToQualifier f ON f.ratingDataId = c.ratingDataId
LEFT JOIN ciqRatingQualifiervalueType g ON g.qualifiervalueid = f.qualifierValueId
LEFT JOIN ciqRatingValueType h ON h.ratingValueId = c.outlookValueId
WHERE 1=1
AND b.ratingTypeId IN ( '130', '131', '126', '254' )
-- and a.companyId = #companyId
AND a.companyId IN
(SELECT distinct TOP 2000000
c.companyId
FROM ciqCompany c
inner join ciqCompanyStatusType cst on cst.companystatustypeid = c.companystatustypeid
inner join ciqCompanyType ct on ct.companyTypeId = c.companyTypeId
inner join refReportingTemplateType rep on rep.templateTypeId = c.reportingtemplateTypeId
inner join refCountryGeo rcg on c.countryId = rcg.countryId
inner join refState rs on rs.stateId = c.stateId
inner join ciqSimpleIndustry sc on sc.simpleIndustryId = c.simpleIndustryId
ORDER BY companyid desc)
ORDER BY companyId DESC, c.ratingdate, b.ratingTypeId, c.ratingStatusIndicator
This will list where there are duplicate companyID's
SELECT companyId, count(*) as Recs
FROM ciqCompany
GROUP BY ciqCompany
HAVING count(*) > 1
I understand that you wish to add a column to the query with the count of each companyId, you can use COUNT() OVER():
select count(a.companyId) over (partition by a.companyId) as companyCount,
<rest of the columns>
from ciqRatingEntity a
join <rest of the query>
This would return in each row the count of the companyId of that row without grouping the results.

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

SQL query MAX functions

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

How to Distinct query result over 2 of 3 columns

I have a query like this:
WITH CTE_KELOMPOKINFORMASI (KelompokInformasi, XBRLItem_ItemId)
AS (
SELECT a.Id AS KelompokInformasi, c.XBRLItem_ItemId
FROM XBRLNamespaces a INNER JOIN XBRLHypercubes b
ON a.XBRLView_ViewId = b.XBRLView_ViewId
INNER JOIN XBRLHypercubeDimensionItems c
ON b.XBRLHypercubeId = c.XBRLHypercube_XBRLHypercubeId
WHERE a.Id like '%KBIK_AAKL%')
SELECT f.KelompokInformasi, e.Name AS DimensionName,
ROW_NUMBER() OVER(PARTITION BY e.Name ORDER BY e.Name DESC) AS 'Number'
FROM XBRLDefinitionRoleDomainItems a
LEFT OUTER JOIN XBRLDefinitionRoleDimensionItems b
ON a.XBRLDefinitionRole_DefinitionRoleId = b.XBRLDefinitionRole_DefinitionRoleId
LEFT OUTER JOIN XBRLItems c ON a.XBRLItem_ItemId = c.ItemId
LEFT OUTER JOIN XBRLLabels d ON a.XBRLItem_ItemId = d.XBRLItem_ItemId
LEFT OUTER JOIN XBRLItems e ON b.XBRLItem_ItemId=e.ItemId
LEFT OUTER JOIN CTE_KELOMPOKINFORMASI f ON b.XBRLItem_ItemId=f.XBRLItem_ItemId
WHERE b.XBRLItem_ItemId=f.XBRLItem_ItemId
and it gives result like this:
Kelompok Informasi DimensionName Number
KBIK_AAKL JWAAKT 1
KBIK_AAKL JWAAKT 2
KBIK_AAKL JWAAKT 3
KBIK_AAKL SNOUPL 1
KBIK_AAKL SNOUPL 2
KBIK_AAKL KOKOLT 1
KBIK_AAKL KOKOLT 2
KBIK_AAKL KOKOLT 3
KBIK_AAKL KOKOLT 4
Is it possible if i DISTINCT my result again by "DimensionName", so i have a result just like this:
KelompokInformasi DimensionName Number
KBIK_AAKL JWAAKT 1
KBIK_AAKL SNOUPL 2
KBIK_AAKL KOKOLT 3
i tried to do distinct like code below but it doesn't work
SELECT DISTINCT DimensionName
FROM (SELECT f.KelompokInformasi, e.Name AS DimensionName,
ROW_NUMBER() OVER(PARTITION BY e.Name ORDER BY e.Name DESC) AS 'Number'
FROM XBRLDefinitionRoleDomainItems a
LEFT OUTER JOIN XBRLDefinitionRoleDimensionItems b
ON a.XBRLDefinitionRole_DefinitionRoleId = b.XBRLDefinitionRole_DefinitionRoleId
LEFT OUTER JOIN XBRLItems c ON a.XBRLItem_ItemId = c.ItemId
LEFT OUTER JOIN XBRLLabels d ON a.XBRLItem_ItemId = d.XBRLItem_ItemId
LEFT OUTER JOIN XBRLItems e ON b.XBRLItem_ItemId=e.ItemId
LEFT OUTER JOIN CTE_KELOMPOKINFORMASI f ON b.XBRLItem_ItemId=f.XBRLItem_ItemId
WHERE b.XBRLItem_ItemId=f.XBRLItem_ItemId)
Use your distinct on the inner subquery and row number them on the outer Select
WITH CTE_KELOMPOKINFORMASI (KelompokInformasi, XBRLItem_ItemId)
AS (
SELECT a.Id AS KelompokInformasi, c.XBRLItem_ItemId
FROM XBRLNamespaces a INNER JOIN XBRLHypercubes b
ON a.XBRLView_ViewId = b.XBRLView_ViewId
INNER JOIN XBRLHypercubeDimensionItems c
ON b.XBRLHypercubeId = c.XBRLHypercube_XBRLHypercubeId
WHERE a.Id like '%KBIK_AAKL%')
Select A.*, ROW_NUMBER() OVER(ORDER BY A.DimensionName DESC) AS 'Number'
FROM (
SELECT distinct f.KelompokInformasi, e.Name AS DimensionName
FROM XBRLDefinitionRoleDomainItems a
LEFT OUTER JOIN XBRLDefinitionRoleDimensionItems b
ON a.XBRLDefinitionRole_DefinitionRoleId = b.XBRLDefinitionRole_DefinitionRoleId
LEFT OUTER JOIN XBRLItems c ON a.XBRLItem_ItemId = c.ItemId
LEFT OUTER JOIN XBRLLabels d ON a.XBRLItem_ItemId = d.XBRLItem_ItemId
LEFT OUTER JOIN XBRLItems e ON b.XBRLItem_ItemId=e.ItemId
LEFT OUTER JOIN CTE_KELOMPOKINFORMASI f ON b.XBRLItem_ItemId=f.XBRLItem_ItemId
WHERE b.XBRLItem_ItemId=f.XBRLItem_ItemId
) AS A
Just Filter with Your Row_Number
Try like this
SELCT KelompokInformasi,DimensionName,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS 'NUMBER' FROM
(
SELECT f.KelompokInformasi, e.Name AS DimensionName,
ROW_NUMBER() OVER(PARTITION BY e.Name ORDER BY e.Name DESC) AS 'RN'
FROM XBRLDefinitionRoleDomainItems a
LEFT OUTER JOIN XBRLDefinitionRoleDimensionItems b
ON a.XBRLDefinitionRole_DefinitionRoleId = b.XBRLDefinitionRole_DefinitionRoleId
LEFT OUTER JOIN XBRLItems c ON a.XBRLItem_ItemId = c.ItemId
LEFT OUTER JOIN XBRLLabels d ON a.XBRLItem_ItemId = d.XBRLItem_ItemId
LEFT OUTER JOIN XBRLItems e ON b.XBRLItem_ItemId=e.ItemId
LEFT OUTER JOIN CTE_KELOMPOKINFORMASI f ON b.XBRLItem_ItemId=f.XBRLItem_ItemId
WHERE b.XBRLItem_ItemId=f.XBRLItem_ItemId
) AS T
WHERE RN = 1
(OR)
SELCT KelompokInformasi,DimensionName,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS 'NUMBER' FROM
(
SELECT f.KelompokInformasi, e.Name AS DimensionName,
FROM XBRLDefinitionRoleDomainItems a
LEFT OUTER JOIN XBRLDefinitionRoleDimensionItems b
ON a.XBRLDefinitionRole_DefinitionRoleId = b.XBRLDefinitionRole_DefinitionRoleId
LEFT OUTER JOIN XBRLItems c ON a.XBRLItem_ItemId = c.ItemId
LEFT OUTER JOIN XBRLLabels d ON a.XBRLItem_ItemId = d.XBRLItem_ItemId
LEFT OUTER JOIN XBRLItems e ON b.XBRLItem_ItemId=e.ItemId
LEFT OUTER JOIN CTE_KELOMPOKINFORMASI f ON b.XBRLItem_ItemId=f.XBRLItem_ItemId
WHERE b.XBRLItem_ItemId=f.XBRLItem_ItemId
GROUP BY f.KelompokInformasi, e.Name
) AS T