Related
I'm obviously new to this and I need some help. I have this code in SQL Server Management Studio.
The error that I get is
Msg 156, Level 15, State 1, Line 38
Incorrect syntax near the keyword 'IF'
If I execute direct select statement instead of using "If" the query is successfully executed.
Please point out what I am missing and where is my mistake.
Thanks a lot.
declare #dateFrom [date] = cast(dateadd(day, -7, getdate()) as [date]);
declare #dateTo [date] = cast(dateadd(day, 28, getdate()) as [date]);
declare #prTypeCode [varchar](10) = null;
declare #ExcludeA [bit] = 0 ;
declare #ExcludeB [bit] = 0;
;with distribution as
(
select *
from [schema1].[Table1]
),
product as
(
select *
from [schema1].[Product]
),
fint as
(
select
*,
(case when CHARINDEX('0%', FIN_ CODE) > 0 then 1 else 0 end) as ZFlag
from [schema1].[FinTab]
),
deal as
(
select
*,
case when (AG_ID = 5 or DE_ID = 6) then 1
else 0 end as Ex_flag
from
[P_ BASE1].[ schema2].[table3]
),
dealersn as
(
select distinct *
from [P_ BASE1].[ schema2].[table4]
),
regionN as
(
select distinct *
from [P_ BASE1].[ schema2].[table5]
),
final as
(
select
d.PRODUCT_CODE, p.PR_NAME, p.PR_TYPE_CODE, p.PR_ACTIVE,
d.FIN_TABLE_CODE, ft.FT_NAME, ft.FT_ACTIVE,
cast(d.SND_TO_DATE as [date]) as SND_TO_DATE,
count(d.SN_ID) as SHOP_COUNT,
min(ft.ZFlag) as ZFlag,
min(ds.Ex_flag) as ExFlag, dn.SND_FULLNAME,rn.REG_NAME
from
distribution d
left outer join
product p on p.PRODUCT_CODE = d.PRODUCT_CODE
left outer join
fint ft on ft. FIN_ CODE = FIN_ CODE
left outer join
deal as ds On d.SN_ID = ds.SHOP_ID
left outer join
dealersn as dn on d.SN_ID = dn.SN_DATA_ID
left outer join
regionN as rn ON ds.REGION_ID = rn.REGION_ID
where
d.SND_TO_DATE between #dateFrom and #dateTo
and (#prTypeCode is null or p.PR_TYPE_CODE = #prTypeCode)
group by
rn.REG_NAME, ds.REGION_ID, ds.SHOP_ID, d.PRODUCT_CODE, p.PR_NAME,
p.PR_TYPE_CODE, p.PR_ACTIVE, d.FIN_TABLE_CODE, ft.FT_NAME,
ft.FT_ACTIVE, d.SND_TO_DATE,dn.SND_FULLNAME
)
IF (#ZeroPercent = 0 AND #LargeChainsOrTushev = 0)
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 0 AND ExFlag = 0
END
ELSE
IF #ZeroPercent = 1 AND #LargeChainsOrTushev = 0
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 1 AND ExFlag = 0
END
ELSE IF #ZeroPercent = 0 AND #LargeChainsOrTushev = 1
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 0 AND ExFlag = 1
END
ELSE
BEGIN
SELECT DISTINCT *
FROM final
END
You have a with statement that "defines" a bunch of tables, the last of which is called final. This is called a CTE (Common Table Expression). You can use CTEs for many reasons, but the important thing is, you have to use the CTE in a query. Instead you define the CTE and then...do nothing.
If you put a line like this:
select * from final
just after the CTE (before the IF), it will run.
I Write the following SQL query to get data order by some condition,
SELECT #NullCount = COUNT(1)
FROM #ServicesForBranch where SortValue IS NULL;
SELECT #ServiceCount = COUNT(1)
FROM Service;
SELECT * FROM #tmp t
WHERE t.IsActive = 1
ORDER BY
CASE WHEN #NullCount = #ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue,t.Name END
But error is showing in this line t.BranchServiceSortValue,t.Name as
incorrect syntax near ','
What I wrote wrong here?
Try this :
SELECT #NullCount = COUNT(1)
FROM #ServicesForBranch
where SortValue IS NULL;
SELECT #ServiceCount = COUNT(1)
FROM Service;
SELECT * FROM #tmp t
WHERE t.IsActive = 1
ORDER BY
(CASE WHEN #NullCount = #ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END),t.Name
Each CASE statement returns only 1 value so you need another one:
ORDER BY
CASE WHEN #NullCount = #ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END,
CASE WHEN #NullCount <> #ServiceCount THEN t.Name END
but if SortValue is unique or you don't mind a secondary sorting on Name then you can simplify to this:
ORDER BY
CASE WHEN #NullCount = #ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END,
t.Name
I have been at this for some time and am frustrated. Below is the complete SQL statement I am trying to execute. Simply put, create a temp table from a UNION Select(s) statements.
I can run the SELECTs with the UNION just fine. I can run the separate SELECTS just fine. I can run separate INSERT INTOs just fine. The moment I add an INSERT INTO SELECT * FROM (...) at the top and close it at the bottom I get a syntax error:
Msg 102, Level 15, State 1, Line 75
Incorrect syntax near ')'.
I was hoping this would be simple, but I tried everything I know to get this to work, and cannot. is there something, perhaps with the UNION that creates the syntax error?
INSERT INTO #Tmp6 SELECT * FROM
(
SELECT
[ItemStatus]
,[Item_Number]
,[Item_Name]
,[Default_Sales_Name]
,[Special_Order_Item]
,[Returnable]
,[Return_Number_Of_Days]
,[Is_Drop_Ship]
,[Is_JIT]
,[Vendor_Name]
,[Vendor_Number]
,[Default_Sales_Price]
,[Cost_Of_Goods]
,[Purchase_Cost]
,[Additional_Cost1_Text]
,[Additional_Cost1_Value]
,[Additional_Cost2_Text]
,[Additional_Cost2_Value]
,[Additional_Cost3_Text]
,[Additional_Cost3_Value]
,[UPC_Value]
,[Weight]
,[DimWeight]
,[Discontinued_Date]
,[Personalization_Template_Number]
,[Harmonized_Code]
,[Base_Category]
,[Sub_Category]
,[End_Category]
,[RowID]
FROM [dbo].[RAIProductsStg] p
WHERE ItemStatus <> 'Discontinued' OR
p.Item_Number IN (SELECT i.Item_Number FROM RAIInventoryStg i WHERE p.Item_Number = i.Item_Number AND Quantity > 0)
UNION
SELECT
[ItemStatus]
,[Item_Number]
,[Item_Name]
,[Default_Sales_Name]
,[Special_Order_Item]
,[Returnable]
,[Return_Number_Of_Days]
,[Is_Drop_Ship]
,[Is_JIT]
,[Vendor_Name]
,[Vendor_Number]
,[Default_Sales_Price]
,[Cost_Of_Goods]
,[Purchase_Cost]
,[Additional_Cost1_Text]
,[Additional_Cost1_Value]
,[Additional_Cost2_Text]
,[Additional_Cost2_Value]
,[Additional_Cost3_Text]
,[Additional_Cost3_Value]
,[UPC_Value]
,[Weight]
,[DimWeight]
,[Discontinued_Date]
,[Personalization_Template_Number]
,[Harmonized_Code]
,[Base_Category]
,[Sub_Category]
,[End_Category]
,[RowID]
FROM [dbo].[RAIProductsStg] p
LEFT JOIN RAIParentChildStg pc ON p.Item_Number = pc.ParentItemNumber
WHERE(LEN(p.Item_Number) = 6 AND p.ItemStatus = 'Discontinued') AND
(pc.ChildItemNumber IN
(SELECT i.Item_Number FROM RAIInventoryStg i
WHERE pc.ChildItemNumber = i.Item_Number AND i.Quantity > 0))
)
Please try this. Put alias after last bracket.
INSERT INTO #Tmp6
SELECT * FROM
(
SELECT
[ItemStatus]
,[Item_Number]
,[Item_Name]
,[Default_Sales_Name]
,[Special_Order_Item]
,[Returnable]
,[Return_Number_Of_Days]
,[Is_Drop_Ship]
,[Is_JIT]
,[Vendor_Name]
,[Vendor_Number]
,[Default_Sales_Price]
,[Cost_Of_Goods]
,[Purchase_Cost]
,[Additional_Cost1_Text]
,[Additional_Cost1_Value]
,[Additional_Cost2_Text]
,[Additional_Cost2_Value]
,[Additional_Cost3_Text]
,[Additional_Cost3_Value]
,[UPC_Value]
,[Weight]
,[DimWeight]
,[Discontinued_Date]
,[Personalization_Template_Number]
,[Harmonized_Code]
,[Base_Category]
,[Sub_Category]
,[End_Category]
,[RowID]
FROM [dbo].[RAIProductsStg] p
WHERE ItemStatus <> 'Discontinued' OR
p.Item_Number IN (SELECT i.Item_Number FROM RAIInventoryStg i WHERE p.Item_Number = i.Item_Number AND Quantity > 0)
UNION
SELECT
[ItemStatus]
,[Item_Number]
,[Item_Name]
,[Default_Sales_Name]
,[Special_Order_Item]
,[Returnable]
,[Return_Number_Of_Days]
,[Is_Drop_Ship]
,[Is_JIT]
,[Vendor_Name]
,[Vendor_Number]
,[Default_Sales_Price]
,[Cost_Of_Goods]
,[Purchase_Cost]
,[Additional_Cost1_Text]
,[Additional_Cost1_Value]
,[Additional_Cost2_Text]
,[Additional_Cost2_Value]
,[Additional_Cost3_Text]
,[Additional_Cost3_Value]
,[UPC_Value]
,[Weight]
,[DimWeight]
,[Discontinued_Date]
,[Personalization_Template_Number]
,[Harmonized_Code]
,[Base_Category]
,[Sub_Category]
,[End_Category]
,[RowID]
FROM [dbo].[RAIProductsStg] p
LEFT JOIN RAIParentChildStg pc ON p.Item_Number = pc.ParentItemNumber
WHERE(LEN(p.Item_Number) = 6 AND p.ItemStatus = 'Discontinued') AND
(pc.ChildItemNumber IN
(SELECT i.Item_Number FROM RAIInventoryStg i
WHERE pc.ChildItemNumber = i.Item_Number AND i.Quantity > 0))
)c
Place the bracket after the second select statement. That should do it.
INSERT INTO TableA
(
SELECT A, B, C
FROM TableB
UNION
SELECT D, E, F
FROM TableC
)
Here's my Count_query:
Declare #yes_count decimal;
Declare #no_count decimal;
set #yes_count=(Select count(*) from Master_Data where Received_Data='Yes');
set #no_count=(Select count(*) from Master_Data where Received_Data='No');
select #yes_count As Yes_Count,#no_count as No_Count,(#yes_count/(#yes_count+#no_count)) As Submission_Count
I am having trouble making joins on these two queries
This is the rest of the query:
Select Distinct D.Member_Id,d.Name,d.Region_Name, D.Domain,e.Goal_Abbreviation,
e.Received_Data, case when Received_Data = 'Service Not Provided' then null
when Received_Data = 'No' then null else e.Improvement end as
Percent_Improvement , case when Received_Data = 'Service Not Provided' then null
when Received_Data = 'No' then null else e.Met_40_20 end as Met_40_20
FROM (
select distinct member_Domains.*,
(case when NoData.Member_Id is null then 'Participating' else ' ' end) as Participating
from
(
select distinct members.Member_Id, members.Name, Members.Region_Name,
case when Domains.Goal_Abbreviation = 'EED Reduction' then 'EED'
When Domains.Goal_Abbreviation = 'Pressure Ulcers' then 'PRU'
when Domains.Goal_Abbreviation = 'Readmissions' then 'READ' else Domains.Goal_Abbreviation end as Domain from
(select g.* from Program_Structure as ps inner join Goal as g on ps.Goal_Id = g.Goal_Id
and ps.Parent_Goal_ID = 0) as Domains
cross join
(select distinct hc.Member_ID, hc.Name,hc.Region_Name from zsheet as z
inner join Hospital_Customers$ as hc on z.CCN = hc.Mcare_Id) as Members
) as member_Domains
left outer join Z_Values_Hospitals as NoData on member_Domains.member_ID = NoData.Member_Id
and Member_Domains.Domain = noData.ReportName) D
Left Outer JOIN
(SELECT B.Member_ID, B.Goal_Abbreviation, B.minRate, C.maxRate, B.BLine, C.Curr_Quarter, B.S_Domain,
(CASE WHEN B.Member_ID IN
(SELECT member_id
FROM Null_Report
WHERE ReportName = B.S_Domain) THEN 'Service Not Provided' WHEN Curr_Quarter = 240 THEN 'Yes' ELSE 'No' END) AS Received_Data,
ROUND((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (((maxRate - minRate) / minRate) * 100) END), .2) AS Improvement,
(CASE WHEN ((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (maxRate - minRate) / minRate END)) <= - 0.4 OR
maxRate = 0 THEN 'Yes' WHEN ((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (maxRate - minRate) / minRate END))
<= - 0.2 OR maxRate = 0 THEN 'Yes' ELSE 'No' END) AS Met_40_20
FROM (SELECT tab.Member_ID, tab.Measure_Value AS minRate, tab.Goal_Abbreviation, A.BLine, tab.S_Domain
FROM Measure_Table_Description AS tab INNER JOIN
(SELECT DISTINCT
Member_ID AS new_memid, Goal_Abbreviation AS new_measure, MIN(Reporting_Period_ID) AS BLine, MAX(Reporting_Period_ID)
AS Curr_Quarter
FROM Measure_Table_Description
WHERE (Member_ID > 1) AND (Measure_Value IS NOT NULL) AND (Measure_ID LIKE '%O%')
GROUP BY Goal_Abbreviation, Member_ID) AS A ON tab.Member_ID = A.new_memid AND tab.Reporting_Period_ID = A.BLine AND
tab.Goal_Abbreviation = A.new_measure) AS B FULL OUTER JOIN
(SELECT tab.Member_ID, tab.Measure_Value AS maxRate, tab.Goal_Abbreviation, A_1.Curr_Quarter
FROM Measure_Table_Description AS tab INNER JOIN
(SELECT DISTINCT
Member_ID AS new_memid, Goal_Abbreviation AS new_measure,
MIN(Reporting_Period_ID) AS BLine, MAX(Reporting_Period_ID)
AS Curr_Quarter
FROM Measure_Table_Description AS Measure_Table_Description_1
WHERE (Member_ID >1) AND (Measure_Value IS NOT NULL) AND (Measure_ID LIKE '%O%')
GROUP BY Goal_Abbreviation, Member_ID) AS A_1 ON tab.Member_ID = A_1.new_memid
AND tab.Reporting_Period_ID = A_1.Curr_Quarter AND
tab.Goal_Abbreviation = A_1.new_measure) AS C ON B.Member_ID = C.Member_ID
WHERE (B.Goal_Abbreviation = C.Goal_Abbreviation) ) E ON D.Member_Id = E.Member_ID AND d.Domain = E.S_Domain
ORDER BY D.Domain,D.Member_ID
How do I get a count of the 'yes'/ (count(yes)+count(no)) for each member_ID as column1 and also display the rank of each member_ID against all the member_IDs in the result as column2. I have come up with a query that generates the count for the entire table, but how do I restrict it each Member_ID.
Thanks for your help.
I haven't taken the time to digest your provided query, but if abstracted to the concept of having an aggregate over a range of data repeated on each row, you should look at using windowing functions. There are other methods, such as using a CTE to do your aggregation and then JOINing back to your detailed data. That might work better for more complex calculations, but the window functions are arguably the more elegant option.
DECLARE #MasterData AS TABLE
(
MemberID varchar(50),
MemberAnswer int
);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 0);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 0);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 1);
-- Method 1, using windowing functions (preferred for performance and syntactical compactness)
SELECT
MemberID,
MemberAnswer,
CONVERT(numeric(19,4),SUM(MemberAnswer) OVER (PARTITION BY MemberID)) / CONVERT(numeric(19,4),COUNT(MemberAnswer) OVER (PARTITION BY MemberID)) AS PercentYes
FROM #MasterData;
-- Method 2, using a CTE
WITH MemberSummary AS
(
SELECT
MemberID,
SUM(MemberAnswer) AS MemberYes,
COUNT(MemberAnswer) AS MemberTotal
FROM #MasterData
GROUP BY MemberID
)
SELECT
md.MemberID,
md.MemberAnswer,
CONVERT(numeric(19,4),MemberYes) / CONVERT(numeric(19,4),MemberTotal) AS PercentYes
FROM #MasterData md
JOIN MemberSummary ms
ON md.MemberID = ms.MemberID;
First thought is: your query is much, much too complicated. I have spent about 10 minutes now trying to make sense of it and haven't gotten anywhere, so it's obviously going to pose a long-term maintenance challenge to those within your organization going forward as well. I would really recommend you try to find some way of simplifying it.
That said, here is a simplified, general example of how to query on a calculated value and rank the results:
CREATE TABLE member (member_id INT PRIMARY KEY);
CREATE TABLE master_data (
transaction_id INT PRIMARY KEY,
member_id INT FOREIGN KEY REFERENCES member(member_id),
received_data BIT
);
-- INSERT data here
; WITH member_data_counts AS (
SELECT
m.member_id,
(SELECT COUNT(*) FROM master_data d WHERE d.member_id = m.member_id AND d.received_data = 1) num_yes,
(SELECT COUNT(*) FROM master_data d WHERE d.member_id = m.member_id AND d.received_data = 0) num_no
FROM member m
), member_data_calc AS (
SELECT
*,
CASE
WHEN (num_yes + num_no) = 0 THEN NULL -- avoid division-by-zero error
ELSE num_yes / (num_yes + num_no)
END pct_yes
FROM member_data_counts
), member_data_rank AS (
SELECT *, RANK() OVER (ORDER BY pct_yes DESC) AS RankValue
FROM member_data_calc
)
SELECT *
FROM member_data_rank
ORDER BY RankValue ASC;
I have a query in sql stored procedure. I want to get record from other query from its id how I do that.
SELECT t.Name ,t.CreatedDate ,t.CreatedBy , t.Amount
,t.Margin ,t.Probability ,t.Id
FROM (SELECT a = 1) a
CROSS JOIN
(SELECT
Name = HirschInternational_MSCRM.dbo.SalesOrderBase.Name
,CreatedDate=HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedOn
,CreatedBy=HirschInternational_MSCRM.dbo.SystemUserBase.FullName
,Amount = totalamount
,Probability=CloseProbability
,Id=SalesOrderId
,Margin=(SELECT ( ISNULL( ((Sum(Price)-Sum(CurrentCost)) / NULLIF( Sum(Price), 0 ))*100, 0 ) )
FROM HirschInternational_MSCRM.dbo.ProductBase
JOIN HirschInternational_MSCRM.dbo.SalesOrderDetailBase
ON HirschInternational_MSCRM.dbo.SalesOrderDetailBase.ProductId = HirschInternational_MSCRM.dbo.ProductBase.ProductId
JOIN HirschInternational_MSCRM.dbo.SalesOrderBase
ON HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId = HirschInternational_MSCRM.dbo.SalesOrderDetailBase.SalesOrderId)
FROM HirschInternational_MSCRM.dbo.SalesOrderBase
JOIN HirschInternational_MSCRM.dbo.OpportunityBase
ON HirschInternational_MSCRM.dbo.SalesOrderBase.Opportunityid = HirschInternational_MSCRM.dbo.OpportunityBase.Opportunityid
JOIN HirschInternational_MSCRM.dbo.SystemUserBase
ON HirschInternational_MSCRM.dbo.SystemUserBase.SystemUserId = HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedBy
WHERE YEAR(HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedOn)=YEAR(GETDATE())
I want Margin from every record I want Output like
It's not entirely clear what you want, but you might be looking for something like
select *
from (your SQL SELECT statement goes here) t1
where id = ?;
I want to get margin of every record how I filter margin query for SalesOrderId
like
Margin=(SELECT ( ISNULL( ((Sum(Price)-Sum(CurrentCost)) / NULLIF( Sum(Price), 0 ))*100, 0 ) )
FROM HirschInternational_MSCRM.dbo.ProductBase
JOIN HirschInternational_MSCRM.dbo.SalesOrderDetailBase
ON HirschInternational_MSCRM.dbo.SalesOrderDetailBase.ProductId = HirschInternational_MSCRM.dbo.ProductBase.ProductId
JOIN HirschInternational_MSCRM.dbo.SalesOrderBase
ON HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId = HirschInternational_MSCRM.dbo.SalesOrderDetailBase.SalesOrderId
Where HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId= //SalesOrderId that I get in main query)
how I pass that SalesOrderId in this query