How can I do Select like this - sql-server-2008-r2

Declare #Result as varchar(max)='';
SELECT DISTINCT #Result = dbo.MaterialTypes.Title + ', '+ #Result
FROM dbo.TempId LEFT OUTER JOIN
dbo.ProductMaterials ON dbo.ProductMaterials.Product = dbo.TempId.Id LEFT OUTER JOIN
dbo.MaterialTypes ON dbo.ProductMaterials.MaterialType = dbo.MaterialTypes.Id LEFT OUTER JOIN
dbo.Products ON dbo.Products.Id = dbo.TempId.Id
WHERE (dbo.Products.IsCollection = 1)
SELECT DISTINCT dbo.TempId.Id AS MaterialCollection_id, #Result
FROM dbo.TempId LEFT OUTER JOIN
dbo.ProductMaterials ON dbo.ProductMaterials.Product = dbo.TempId.Id LEFT OUTER JOIN
dbo.MaterialTypes ON dbo.ProductMaterials.MaterialType = dbo.MaterialTypes.Id LEFT OUTER JOIN
dbo.Products ON dbo.Products.Id = dbo.TempId.Id
WHERE (dbo.Products.IsCollection = 1)
this query is work, but i can't create View, based on this query. Please help!

As murtaza says you can create a Stored Procedure for this, or if you want to use this as a view you can create a Table-valued Function which you can use other views and joins.
http://msdn.microsoft.com/en-us/library/ms191165.aspx

Related

How can I use value from main select in Left Outer Join select - T-SQL

In my below T-SQL Query I need to use EFP_MessageCenter.MessageSender from my main SELECT in the SELECT in my LEFT OUTER JOIN as the value where I have placed <MessageSenderInitials>.
When I set (EFP_MessageCenter_1.MessageSender = EFP_MessageCenter.MessageSender) or (EFP_MessageCenter_1.MessageSender = MessageSenderInitials) I get the error The multi-part identifier "EFP_MessageCenter.MessageSender" could not be bound.
How can I get this to work?
SELECT LOWER(EFP_MessageCenter.MessageSender) AS MessageSenderInitials
, MAX(SenderInfo.FullName) AS SenderFullName
, MAX(SenderInfo.ProfilePicture) AS SenderProfilePicture
, MAX(EFP_MessageCenter_Receiver.UserID) AS ReceiverID
, MAX(EFP_MessageCenter.MessageTimestamp) AS ChangeDate
, COUNT(DisplayCountSelect.Displayed) AS CountNonReadMessages
FROM EFP_MessageCenter_Receiver
INNER JOIN EFP_MessageCenter ON EFP_MessageCenter_Receiver.MessageID = EFP_MessageCenter.id
INNER JOIN EFP_EmploymentUser AS SenderInfo ON EFP_MessageCenter.MessageSender = SenderInfo.Initials
LEFT OUTER JOIN
(SELECT EFP_MessageCenter_Receiver_1.Displayed, EFP_MessageCenter_Receiver_1.UserID, EFP_MessageCenter_1.MessageSender
FROM EFP_MessageCenter AS EFP_MessageCenter_1
INNER JOIN EFP_MessageCenter_Receiver AS EFP_MessageCenter_Receiver_1 ON EFP_MessageCenter_1.id = EFP_MessageCenter_Receiver_1.MessageID
WHERE (EFP_MessageCenter_Receiver_1.Displayed = 0) AND (EFP_MessageCenter_Receiver_1.UserID = 65) AND (EFP_MessageCenter_1.MessageSender = '<MessageSenderInitials>'))
AS DisplayCountSelect
ON DisplayCountSelect.UserID = EFP_MessageCenter_Receiver.UserID
WHERE (EFP_MessageCenter_Receiver.UserID = 65) AND (EFP_MessageCenter.MessageType = 'SPECIFIC')
GROUP BY EFP_MessageCenter.MessageSender
ORDER BY ChangeDate DESC
I've made a slight refactor of your query and changed the outer join to an an outer apply
It's not going to be 100% working I'm sure but should allow you to tweak it and include the correlation you need to.
I suspect you could move the CountNonReadMessages to a count(*) in the apply and possibly remove the aggregation, but that's just a guess.
select Lower(mc.MessageSender) as MessageSenderInitials
, Max(s.FullName) as SenderFullName
, Max(s.ProfilePicture) as SenderProfilePicture
, Max(mr.UserID) as ReceiverID
, Max(mc.MessageTimestamp) as ChangeDate
, Count(s.Displayed) as CountNonReadMessages
from EFP_MessageCenter_Receiver mr
join EFP_MessageCenter mc on mr.MessageID = mc.id
join EFP_EmploymentUser eu on mc.MessageSender = eu.Initials
outer apply (
select mr.Displayed
from EFP_MessageCenter mcx
join EFP_MessageCenter_Receiver mrx on mcx.id = mrx.MessageID
where mrx.Displayed = 0
and mrx.UserId=mr.UserId
and mcx.UserID = 65 /* this should probably be correlated */
and mcx.MessageSender = '<MessageSenderInitials>'
) s
where mr.UserID = 65 and mc.MessageType = 'SPECIFIC'
group by mc.MessageSender
order by ChangeDate desc

TSQL 2008 How to make columns for views unique

I have a query I am trying to save as a view but SSMS returns an error stating there are multiple columns with the same name.
I have tried to rename the affected columns as an alias but without success.
Column names in each view or function must be unique. Column name 'codemanQuestionID' in view or function 'vwBlocks' is specified more than once.
create view vwBlocks as
SELECT
LUConstructionType.codemanOptionID AS LUConstruction_codemanOptionID
, LUFascias.codemanOptionID AS LUFascias_codemanOptionID
, Block.windowsID
, LUWindows.windows
, LUWindows.codemanQuestionID AS codemanQuestion_ID
, Block.externalDoorID
, LUExternalDoor.externalDoor
, LUExternalDoor.codemanOptionID as LUExternal_codemanOptionID
FROM Block LEFT OUTER JOIN
LUOwnership ON Block.ownershipID = LUOwnership.ownershipID LEFT OUTER JOIN
LULocalAuthority ON Block.localAuthorityID = LULocalAuthority.authorityTypeID LEFT OUTER JOIN
LUConstructionType ON Block.constructionTypeID = LUConstructionType.constructionTypeID LEFT OUTER JOIN
LUTV ON Block.TVID = LUTV.TVID LEFT OUTER JOIN
LUSatellite ON Block.satelliteID = LUSatellite.satelliteID LEFT OUTER JOIN
LUPlayArea ON Block.playArea = LUPlayArea.playAreaID LEFT OUTER JOIN
LURoofCovering ON Block.roofCoveringID = LURoofCovering.roofCoveringID LEFT OUTER JOIN
LUFascias ON Block.fasciasID = LUFascias.fasciasID LEFT OUTER JOIN
LUWindows ON Block.windowsID = LUWindows.windowsID LEFT OUTER JOIN
LUExternalDoor ON Block.externalDoorID = LUExternalDoor.externalDoorID LEFT OUTER JOIN
LUcontractorInfo ON Block.contractorInfoID = LUcontractorInfo.contractorID LEFT OUTER JOIN
LUagentInfo ON Block.agentInfoID = LUagentInfo.agentID LEFT OUTER JOIN
LULandlord ON Block.LandlordID = LULandlord.landlordID LEFT OUTER JOIN
LUblockStatus ON Block.blockStatusID = LUblockStatus.blockStatusID LEFT OUTER JOIN
LUPropertyGroup ON Block.propertyGroup = LUPropertyGroup.propertyGroupID LEFT OUTER JOIN
LUCommunalBoilerType ON Block.communalBoilerType = LUCommunalBoilerType.communalBoilerID LEFT OUTER JOIN
LUExternalAreaManagedBy ON Block.externalAreaManagedBy = LUExternalAreaManagedBy.managedByID LEFT OUTER JOIN
LUgasBoilerMakeModel ON Block.CommBoilerMakeModelID = LUgasBoilerMakeModel.makeModelId LEFT OUTER JOIN
LUMaintenanceResp ON Block.maintenanceRepID = LUMaintenanceResp.maintenanceRepID
Can anybody recommend a solution please?
Thanks for any help in advance.
I'm not seeing codemanQuestionID twice. Here's some advice that has helped me a ton avoid and/or troubleshoot issues like this.
There are at least four ways to alias a column:
(expression) AS ((alias))
((alias)) = (expression)
WITH ((cte name)) ((alias1), (alias2),...
FROM ((subquery)) AS ((alias1>),(alias2,...
AS is the worst IMO. Its sloppy and confusing, especially when you don't include AS. The aliasing style I usually go with is:
SELECT
col1 = <expression>,
col2 = <expression>,
colABC = <expression>
FROM schema.table1 AS t1
JOIN schema.table2 AS t2;
This has made debugging waaay easier.

Why does not adding distinct in this query produce duplicate rows?

This query was taken from a Rails application log...I'm trying to edit a massive postgresql statement I didn't write....If I don't add a distinct keyword after the SELECT, 2 duplicate rows appear for each braintree account. Why is this and is there another way to avoid having to use the distinct to avoid duplicates?
EDIT: I understand what distinct is supposed to do, the reason I'm asking is that it doesn't generate duplicates for other toy lines. By other toy lines, this query is building a "table" for a particular toy id (this specific example toys.id = 12). How do I figure out where the duplicate rows are being generated?
SELECT accounts.braintree_account_id as braintree_account_id,
accounts.braintree_account_id as braintree_account_id, format('%s %s', addresses.first_name,
addresses.last_name) as shipping_address_full_name,
users.email as email, addresses.line_1 as shipping_address_line_1,
addresses.line_2 as shipping_address_line_2, addresses.city as
shipping_address_city, addresses.state as shipping_address_state,
addresses.zip as shipping_address_zip_code, addresses.country
as shipping_address_country, CASE WHEN xy_shirt IS NULL THEN '' ELSE xy_shirt END, plans.name as plan_name, toys.sku as sku, to_char(accounts.created_at, 'MM/DD/YYYY HH24:MM:SS') as
account_created_at,
to_char(accounts.next_assessment_at, 'MM/DD/YYYY HH24:MM:SS') as account_next_assessment_at,
accounts.account_status as account_status FROM \"accounts\" INNER JOIN \"addresses\" ON
\"addresses\".\"id\" = \"accounts\".\"shipping_address_id\" AND \"addresses\".\"type\" IN
('ShippingAddress') LEFT OUTER JOIN shipping_methods ON
shipping_methods.account_id = accounts.id LEFT OUTER JOIN plans ON
accounts.plan_id = plans.id
LEFT OUTER JOIN users ON
accounts.user_id = users.id LEFT OUTER JOIN toys ON plans.toy_id = toys.id
LEFT OUTER JOIN account_variations ON accounts.id =
account_variations.account_id LEFT OUTER JOIN variations ON
account_variations.variation_id = variations.id
LEFT OUTER JOIN
choice_value_variations ON variations.id =
choice_value_variations.variation_id
LEFT OUTER JOIN choice_values ON
choice_value_variations.choice_value_id = choice_values.id LEFT OUTER
JOIN choice_types ON choice_values.choice_type_id = choice_types.id
LEFT
OUTER JOIN choice_type_toys ON choice_type_toys.toy_id = toys.id
AND choice_type_toys.choice_type_id = choice_types.id
LEFT OUTER JOIN
(SELECT * FROM crosstab('SELECT accounts.id, choice_types.id,
choice_values.presentation FROM accounts\n
LEFT JOIN account_variations ON
accounts.id=account_variations.account_id\n
LEFT JOIN variations ON account_variations.variation_id=variations.id\n
LEFT JOIN choice_value_variations ON
variations.id=choice_value_variations.variation_id\n
LEFT JOIN choice_values ON
choice_value_variations.choice_value_id=choice_values.id\n
LEFT JOIN choice_types ON choice_values.choice_type_id=choice_types.id
ORDER BY 1,2',\n 'select distinct choice_types.id
from choice_types JOIN choice_values ON choice_values.choice_type_id =
choice_types.id JOIN choice_value_variations ON
choice_value_variations.choice_value_id = choice_values.id JOIN
variations ON choice_value_variations.variation_id = variations.id JOIN choice_type_toys ON choice_type_toys.choice_type_id = choice_types.id JOIN toys ON toys.id = choice_type_toys.toy_id
where toys.id=12 ORDER
BY choice_types.id ASC')\n
AS (account_id int, xy_shirt
VARCHAR)) account_variation_view\n ON
accounts.id=account_variation_view.account_id WHERE
\"accounts\".\"account_status\" = 'active' AND
\"addresses\".\"flagged_invalid_at\" IS NULL AND \"toys\".\"id\" = 12
AND (NOT EXISTS (SELECT \"account_skipped_months\".* FROM
\"account_skipped_months\" WHERE
\"account_skipped_months\".\"month_year\" = 'JUL2016' AND
(account_skipped_months.account_id = accounts.id)))"
The purpose of using DISTINCT in a SELECT statement is to eliminate duplicate rows.

sql, group a query with no aggregations and multiple tables

I need to group the query below by dda.LA and need to display all the columns listed in the select but almost none of them are aggregated. i don't know what the syntax to get around this is and i can not find a post that shows this syntax (most examples only have one table, two at tops).
Select dda.a,
dda.b,
dda.c,
dda.d,
dda.e,
dda.f,
dda.g,
dda.h,
dda.i,
dda.j,
dda.k,
dda.l,
dda.m,
dda.n,
dda.o,
dda.p,
dda.r,
dda.u,
dda.LA,
dd.aa,
coalesce(apn.apn,Pt.z) as abc,
coalesce(apn.v,Pt.y) as def,
'RFN' RowFocusIndicator ,
'SRI' SelectRowIndicator ,
'Y' Expanded ,
Convert(Int, Null) SortColumn
From dda (NoLock)
Inner Join dd (NoLock) On dda.d = dd.q and dda.e = dd.e
Left Outer Join apn (nolock) on dda.r = apn.r
Left Outer Join Pt (nolock) on dda.s = Pt.t
Where 1 = 1
And dda.u = (Select Min(c.w)
From c (NoLock)
Where c.x = dda.s)
Thanks!
Just add this to any column that you want to aggregate by:
AggregatedColumnName = Aggregation(fieldToAggregate) Over (Partition By dda.LA)
ex.
aCount = Count(dda.a) Over (Partition By dda.LA)

PostgreSQL Same Table Left Outer Join With Multiple Tables

I have a table which needs to left outer joined with two different tables. When I put the table twice in the query and join it with it self in the where clause (like the sentence below) it works. I think this should not be the correct way. How can I write the select statement and outer join the table with multiple different tables?
SELECT cols."COLUMN_NAME"
, COALESCE(translations."COLUMN_LANG_TITLE",cols."COLUMN_TITLE") AS "COLUMN_TITLE"
, options."OPTION_DESC"
FROM
"EXTAPP_SETUP"."OBJECT_COLUMNS_TAB" cols LEFT OUTER JOIN "EXTAPP_SETUP"."COLUMN_LANG_TITLES_TAB" translations
ON translations."EXTAPP_ID" = cols."EXTAPP_ID" and translations."OBJECT_NAME" = cols."OBJECT_NAME" and translations."COLUMN_NAME" = cols."COLUMN_NAME" and translations."LANGUAGE_CODE" = 'fr',
"EXTAPP_SETUP"."OBJECT_COLUMNS_TAB" cols2 LEFT OUTER JOIN "EXTAPP_SETUP"."COL_FIX_OPTIONS_TAB" options
ON options."EXTAPP_ID" = cols2."EXTAPP_ID" and options."OBJECT_NAME" = cols2."OBJECT_NAME" and options."COLUMN_NAME" = cols2."COLUMN_NAME"
WHERE cols."EXTAPP_ID" = cols2."EXTAPP_ID" and cols."OBJECT_NAME" = cols2."OBJECT_NAME" and cols."COLUMN_NAME" = cols2."COLUMN_NAME"
You can use subsequent left joins.
Since you are not realy using your cols2 table, you can eliminate it from the query. This would also eliminate the where clause, because you don't need to join the cols table with itself
SELECT cols."COLUMN_NAME"
, COALESCE(translations."COLUMN_LANG_TITLE",cols."COLUMN_TITLE") AS "COLUMN_TITLE"
, options."OPTION_DESC"
FROM "EXTAPP_SETUP"."OBJECT_COLUMNS_TAB" cols
LEFT OUTER JOIN "EXTAPP_SETUP"."COLUMN_LANG_TITLES_TAB" translations
ON translations."EXTAPP_ID" = cols."EXTAPP_ID"
and translations."OBJECT_NAME" = cols."OBJECT_NAME"
and translations."COLUMN_NAME" = cols."COLUMN_NAME"
and translations."LANGUAGE_CODE" = 'fr'
LEFT OUTER JOIN "EXTAPP_SETUP"."COL_FIX_OPTIONS_TAB" options
ON options."EXTAPP_ID" = cols."EXTAPP_ID"
and options."OBJECT_NAME" = cols."OBJECT_NAME"
and options."COLUMN_NAME" = cols."COLUMN_NAME"