When I run the selects below, I do not get Field3 in the result set, why?
Select
a.Field1,
a.Field2,
a.Field3,
sum(IsNull(a.Field4, 0)) AS SomeAlias1,
a.SomeField5,
a.SomeField6,
a.SomeField7
From SomeTable a
INNER JOIN SomeView1 v on v.au = a.au
inner join (select Username, House from Users userBuildings where UserName = #UserName) as userHouses on userHouses.au = a.au
WHERE
(((where claus logic here....
Group BY a.Field1,
a.Field2,
a.SomeAlias1,
a.Field3,
a.Field4,
a.Field5,
a.Field6,
a.Fielf7
)
Select
transBudget.Field1,
transBudget.Field2,
transDiscount.Field4,
... some other fields...
IsNull(transDiscount.Actual, 0) - IsNull(transBudget.Actual, 0) AS Variance
from (Select * from Transactdions Where TransDesc = 'Budget') AS transBudget
FULL OUTER JOIN
(Select * from Transactions Where TransDesc = 'Discount') AS transDiscount
ON transBudget.Market = transDiscount.Market AND transBudget.SubMarket = transDiscount.SubMarket
I see every field except Field3 for some reason and it's beyond me how the heck this can happen.
In the second part of your query, you are missing field 3.
Select
transBudget.Field1,
transBudget.Field2,
transDiscount.Field4,
... some other fields...
IsNull(transDiscount.Actual, 0)
You appear to have two separate SQL queries there. The first one contains Field3, but the second one does not.
Related
We have an organization that can have more than one customer type basically. However, what a user wants to see is either the partner or direct type (customer type is either Direct, Partner1, Partner2, or Partner3 but can be direct plus a partner value but only can be one of the partner values). So if a customer is both (ex: Direct and Partner1) they just want the type that is a partner (ex: Partner1). So I tried splitting out partners only into one temp table from a few tables joining together different org data. I have the same query without any limit pulling into a different temp table. Then I calculate count and put that into a temp table. Then I tried gathering data from all the temp tables. That is where I run into trouble and lose some of the customers where the type is direct (I have a image link below for a directcustomer and a customer who is both). I have been out of SQL for a bit so this one is throwing me...I figure the issue is the fact that I have a case statement referencing a table that a direct customer will not exist in (#WLPO). However I am not sure how to achieve pulling in these customers while also only selecting which partner type it is for a customer that has a partner and is also direct. FYI using MSSMS for querying.
If OBJECT_ID('tempdb..#WLPO') IS NOT NULL
DROP TABLE #WLPO
IF OBJECT_ID('tempdb..#org') IS NOT NULL
DROP TABLE #org
IF OBJECT_ID('tempdb..#OrgCount') IS NOT NULL
DROP TABLE #OrgCount
IF OBJECT_ID('tempdb..#cc') IS NOT NULL
DROP TABLE #cc
Select
o.OrganizationID,
o.OrganizationName,
os.WhiteLabelPartnerID,
s.StateName
INTO #WLPO
from [Org].[Organizations] o
join [Org].[OrganizationStates] os on o.OrganizationID=os.OrganizationID --and os.WhiteLabelPartnerID = 1
join [Lookup].[States] s on os.StateID = s.StateID
join [Org].[PaymentOnFile] pof on pof.OrganizationID=o.OrganizationID
where os.WhiteLabelPartnerID in (2,3,4)
and os.StateID in (1, 2, 3)
and o.OrganizationID = 7613
select * from #WLPO
Select
o.OrganizationID,
o.OrganizationName,
os.WhiteLabelPartnerID,
s.StateName
INTO #org
from [Org].[Organizations] o
join [Org].[OrganizationStates] os on o.OrganizationID=os.OrganizationID --and os.WhiteLabelPartnerID = 1
join [Lookup].[States] s on os.StateID = s.StateID
join [Org].[PaymentOnFile] pof on pof.OrganizationID=o.OrganizationID
where 1=1--os.WhiteLabelPartnerID = 1
and os.StateID in (1, 2, 3)
and o.OrganizationID = 7613
select * from #org
Select
OrganizationID,
count(OrganizationID) AS CountOrgTypes
INTO #OrgCount
from #org
where OrganizationID = 7613
group by OrganizationID
select * from #OrgCount
Select distinct
ct.OrganizationID,
ok.OrganizationName,
ct.CountOrgTypes,
case when ct.CountOrgTypes = 2 then wlp.WhiteLabelPartnerID
when ct.CountOrgTypes = 1 then ok.WhiteLabelPartnerID
END AS CustomerTypeCode,
case when ct.CountOrgTypes = 2 then wlp.StateName
when ct.CountOrgTypes = 1 then ok.StateName END As OrgState
INTO #cc
from #org ok
left join #WLPO wlp on wlp.OrganizationID=ok.OrganizationID
join #OrgCount ct on wlp.OrganizationID=ct.OrganizationID
select * from #cc
Select
OrganizationID,
OrganizationName,
CountOrgTypes,
case when CustomerTypeCode = 1 then 'Direct'
when CustomerTypeCode = 2 then 'Partner1'
when CustomerTypeCode = 3 then 'Partner2'
when CustomerTypeCode = 4 then 'Partner3' ELSE Null END AS CustomerType,
OrgState
from #cc
order by OrganizationName asc
DirectCustomer
CustomerwithBoth
how to i get alias name for my query. Below i am using spring boot with hibernate JPA native query. What i want is to get alias name cbpartnerid as WHERE parameter, because i get c_b_partner from 2 table with condition.
But spring giver me error this :
ERROR 2021-02-26 06:00:02.492 [http-nio-8080-exec-9] o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions(142) - ERROR: column "cbpartnerid" does not exist
i hope can solve this issue without change overall query or modify backend code.
here are my native query :
(CASE
WHEN i.transaction = 'SALES' OR i.transaction = 'CUSTOMER_RETURN' THEN j.c_bpartner_id
WHEN i.transaction = 'INVENTORY_OUT' OR i.transaction = 'INVENTORY_OUT' THEN l.c_bpartner_id
ELSE null
END) AS **cbpartnerid**
FROM so_transaction i
LEFT JOIN so_orderline j ON j.so_orderline_id = i.so_orderline_id LEFT JOIN so_inventoryline k ON k.so_inventoryline_id = i.so_inventoryline_id
LEFT JOIN so_inventory l ON l.so_inventory_id = k.so_inventory_id
GROUP BY i.created, i.transaction, i.m_product_id, i.productname, i.createdby, **cbpartnerid** ORDER BY i.m_product_id DESC ```
The easy solution is a subquery.
Your code, reduced to the essential, looks like
SELECT /* complicated expression */ AS alias,
/* other columns */
FROM atable
GROUP BY alias;
This can be rewritten to
SELECT alias, /* other columns */
FROM (SELECT /* complicated expression */ AS alias,
/* other columns */
FROM atable) AS subq
GROUP BY alias;
SELECT i.created, i.transaction, i.m_product_id, i.productname, i.createdby,
(CASE
WHEN i.transaction = 'SALES' OR i.transaction = 'CUSTOMER_RETURN' THEN j.c_bpartner_id
WHEN i.transaction = 'INVENTORY_OUT' OR i.transaction = 'INVENTORY_OUT' THEN l.c_bpartner_id
ELSE null
END) AS **cbpartnerid**
FROM so_transaction i
LEFT JOIN so_orderline j ON j.so_orderline_id = i.so_orderline_id LEFT JOIN so_inventoryline k ON k.so_inventoryline_id = i.so_inventoryline_id
LEFT JOIN so_inventory l ON l.so_inventory_id = k.so_inventory_id
GROUP BY i.created, i.transaction, i.m_product_id, i.productname, i.createdby, **cbpartnerid** ORDER BY i.m_product_id DESC ```
I'm trying to find out how to get JSON object results of selected rows, and not to show duplicated rows.
My current query:
SELECT DISTINCT ON (vp.id) jsonb_agg(jsonb_build_object('affiliate',a.*)) as affiliates, jsonb_agg(jsonb_build_object('vendor',vp.*)) as vendors FROM
affiliates a
INNER JOIN related_affiliates ra ON a.id = ra.affiliate_id
INNER JOIN related_vendors rv ON ra.product_id = rv.product_id
INNER JOIN vendor_partners vp ON rv.vendor_partner_id = vp.id
WHERE ra.product_id = 79 AND a.is_active = true
GROUP BY vp.id
The results that I receive from this is:
[
affiliates: {
affiliate: affiliate1
affiliate: affiliate2
},
vendors: {
vendor: vendor1,
vendor: vendor1,
}
As you can see in the second record, vendor is still vendor1 because there are no more results, so I'd like to also know if there's a way to remove duplicates.
Thanks.
First point : the result you display here above doesn't conform the json type : the keys are not double-quoted, the string values are not double-quoted, having dupplicated keys in the same json object ('{"affiliate": "affiliate1", "affiliate": "affiliate2"}' :: json) is not be accepted with the jsonb type (but it is with the json type).
Second point : you can try to add the DISTINCT key word directly in the jsonb_agg function :
jsonb_agg(DISTINCT jsonb_build_object('vendor',vp.*))
and remove the DISTINCT ON (vp.id) clause.
You can also add an ORDER BY clause directly in any aggregate function. For more information, see the manual.
You could aggregate first, then join on the results of the aggregates:
SELECT a.affiliates, v.vendors
FROM (
select af.id, jsonb_agg(jsonb_build_object('affiliate',af.*)) as affiliates
from affiliates af
group by af.id
) a
JOIN related_affiliates ra ON a.id = ra.affiliate_id
JOIN related_vendors rv ON ra.product_id = rv.product_id
JOIN (
select vp.id, jsonb_agg(jsonb_build_object('vendor',vp.*)) as vendors
from vendor_partners vp
group by vp.id
) v ON rv.vendor_partner_id = v.id
WHERE ra.product_id = 79
AND a.is_active = true
I Have here firebird query and I dont think if this is correct.
SELECT
COUNT(STATUS) FROM(SELECT STATUS FROM T_TABLE2 WHERE STATUS = 'FAIL') AS FAIL,
DEVICENAME,
SITE_NUM,
COUNT(TEST_NUM)
FROM T_TABLE2 A
INNER JOIN T_TABLE1 B
ON A.TBL1_ID = B.ID
WHERE B.DEVICENAME = 'TANM1A009A_P28'
AND A.TEST_NUM = 'T810'
GROUP BY
DEVICENAME,
TESTER,
SITE_NUM
I want to count the row of TEST_NUM even if it has FAIL value and I also want to count the STATUS that has FAIL value.
Thanks
I really do not know FireBird but from MSSQL point of view why don'y you try this??
SELECT
COUNT(A.STATUS) as 'FAIL',
B.DEVICENAME,
(TableofYourSitenum)SITE_NUM, -- i do no know what table this from
(TableofYourTestnum)COUNT(TEST_NUM) as 'TESTNUM COUNT' --and this also you need to put the table name,
FROM T_TABLE2 A
INNER JOIN T_TABLE1 B
ON A.TBL1_ID = B.ID
WHERE B.DEVICENAME = 'TANM1A009A_P28'
AND A.TEST_NUM = 'T810'
GROUP BY
A.STATUS,
(TableofYourTestnum)TESTNUM
In my database, for stores that have no rating from Reseller Ratings, they still have an entry but have -1.0 instead of a number between 0.0 and 10.0. The following query results in -10.00 showing up in my view for those stores with -1.0. Instead, I would like either nothing or a - showing up in its place, but I'm not very comfortable with implementing embedded if-statements in my view. Here is my current view.
CREATE VIEW myview AS
SELECT co_url_name AS company_url, score_combined AS stella_score, trunc(score*10, 2) AS bizrate_score,
(SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score
FROM ss_profile_co AS s LEFT OUTER JOIN "resellerRatings_ratings" AS r
ON s.id = r.company_id
LEFT OUTER JOIN (SELECT * FROM bizrate_bizrate_ratings WHERE score_name = 'Overall rating') AS b
ON s.id = b.fk_co_id
ORDER BY co_url_name ASC;
The line (SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score is the one that returns the negative numbers (or, for valid entries, will return a score between 0.00 and 100.00).
Obviously, I could simply remove these entries from the database that result in this, but it's half a learning experience and half out of my hands to do so anyways.
I appreciate the help!
EDIT: Attempted an embedded if but not surprisingly got an error.
IF (SELECT trunc("lifetimeRating"*10, 2)) = -10.00 THEN NULL ELSE (SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score
EDIT2: Figured it out. Line in question is as follows:
(SELECT trunc("lifetimeRating"*10, 2) WHERE trunc("lifetimeRating"*10, 2) > 0) AS resellerrating_score
/foreveralone
Could look like this:
CREATE VIEW myview AS
SELECT co_url_name AS company_url
,score_combined AS stella_score
,trunc(score * 10, 2) AS bizrate_score
,CASE WHEN "lifetimeRating" < 0
THEN NULL
ELSE trunc("lifetimeRating" * 10, 2)
END AS resellerRating_score
FROM ss_profile_co s
LEFT JOIN "resellerRatings_ratings" r ON r.company_id = s.id
LEFT JOIN bizrate_bizrate_ratings b ON b.score_name = 'Overall rating'
AND b.fk_co_id = s.id
ORDER BY co_url_name;
Major points
Concerning your core question: the sub-select without a FROM clause serves no purpose. I simplified that and use a CASE statement instead.
I also simplified your LEFT JOIN to bizrate_bizrate_ratings. No sub-select necessary either. I pulled the WHERE clause up into the JOIN condition. Simpler and faster.
I would advise not to use mixed case identifiers, so you never have to use double quotes. (This probably makes #Daniels comment invalid, because lifetimerating != "lifetimeRating"