SQL Server "No column name was specified" - But it was - sql-server

I have a query that runs in SQL Server (using Visual Studio 19), but when I try to run it using Microsoft Query in Excel, I get the error
"No column name was specified for column 5 of 'bv'.
"No column name was specified for column 6 of 'bv'.
"No column name was specified for column 7 of 'bv'.
Statement(s) could not be prepared.
As you can see below, I alias columns 5, 6, and 7 (Pieces, BatchValue, Multiplier). In addition, the fact that this query runs in Visual Studio indicates I haven't gotten this egregiously wrong.
WITH bv AS
(
SELECT
b.BatchID, b.BatchDate, b.BatchName, b.Price AS Cost,
SUM(bh.QtyFound) AS Pieces,
SUM(ps.StrategyPrice * QtyFound) AS BatchValue,
IIF(b.Price = 0, 0, SUM(ps.StrategyPrice * QtyFound) / b.Price) AS Multiplier,
b.Active
FROM
Inventory.Batches b
JOIN
Inventory_Item_History_Summary bh ON b.BatchID = bh.BatchID
JOIN
Selling.Price_Strategy_Table ps ON LEFT(bh.ItemType, 1) = LEFT(ps.ItemType, 1)
AND bh.ItemNum = ps.ItemNo
AND bh.ColorID = ps.Color
AND bh.BLCond = ps.Cond
GROUP BY
b.BatchID, b.BatchDate, b.BatchName, Price, Active
)
SELECT
SUM(p.StrategyPrice * h.QtyFound) / SUM(p.StrategyPrice * IIF(bv.Multiplier = 0, 0, h.QtyFound / bv.Multiplier)) AvgMultiplier
FROM
Inventory.Locations l
JOIN
Inventory_Item_History_Summary h ON h.LocationID = l.LocationID
JOIN
Selling.Price_Strategy_Table p ON LEFT(h.ItemType, 1) = LEFT(p.ItemType, 1)
AND h.ItemNum = p.ItemNo
AND h.ColorID = p.Color
AND h.BLCond = p.Cond
JOIN
bv ON h.BatchID = bv.BatchID
WHERE
l.Cond = 'U'
AND bv.cost > 0
AND bv.Active = 0
What have I done wrong to cause it not to run in Microsoft Query? It's worth noting that I have another query on the same worksheet that uses the exact same bv subquery with no issues

Related

SQL Server Equivalent method for: sys_connect_by_path

My SQL Server query below fails on:
sys_connect_by_path(folder_names.name, '//') "PATH"
I believe it was created in Oracle. Can someone help replace that bit of code with the 2016 SQL Server equivalent ?
select -- report, package,
path
from (
select report_names.name "REPORT"
, sys_connect_by_path(folder_names.name, '//') "PATH"
, package_names.name "PACKAGE"
from cognos_cs.cmobjects folders
join cognos_cs.cmobjnames folder_names on folders.cmid = folder_names.cmid and folder_names.isdefault = 1
left join cognos_cs.cmobjects reports on folders.cmid = reports.pcmid and reports.classid = 10
left join cognos_cs.cmobjnames report_names on reports.cmid = report_names.cmid and report_names.isdefault = 1
left join cognos_cs.cmrefnoord1 packages on reports.cmid = packages.cmid and packages.propid = 31
left join cognos_cs.cmobjnames package_names on packages.refcmid = package_names.cmid and package_names.isdefault = 1
where folders.classid = 1
start with folders.cmid = 2
connect by prior folders.cmid = folders.pcmid
) group by -- report, package,
path
order by path
;

SQL Query for list within select where field = value and otherfield = othervalue

I need to fudge an existing SQL Server procedure rather quickly. It's a bit of a hack job but needs must.
I need for the following to return a list of voucher codes and invoice numbers rather than just one row of data where the comment is (in the WHERE clause):
SELECT TOP 10
IH.INH_Voucher AS [ID], IH.COY_ID AS COY_ID,
IH.INH_DateSupInv AS ORD_UpdatedOn,
V.VES_ID, V.VES_IMOnumber, IH.INH_Order,
IH.INH_ID AS ORD_ID, IH.INH_INDID
FROM
InvoiceHDR IH (NOLOCK)
INNER JOIN
VESSACCOMP VA ON IH.COY_ID = VA.COY_ID
INNER JOIN
Vessel V ON VA.VES_ID = V.VES_ID
WHERE
v.VSS_ID IN ('01') AND
(IH.INH_Status >= 20 AND IH.INH_Status <= 40) AND
--IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532' NEED LIST
IH.INH_INDID IS NOT NULL
So I would need
Voucher = '1700CH' AND SupInv = '1235' AND
Voucher = '180CH' AND SupInv = '1111' AND
And so on for many matching VoucherCodes and InvoiceCodes.
I hope this is clear?
Thanks.
You can apply the following WHERE clause to your query:::
WHERE
v.VSS_ID IN ('01') AND
(IH.INH_Status BETWEEN 20 AND 40) AND
((IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532')
OR (IH.INH_Voucher = '180CH' AND IH.INH_SupInv = '1111'))
AND IH.INH_INDID IS NOT NULL

how to for each loop on data table within another datatable

I have a web poll application that reads and processes orders from sql server back end and inserts into windss(jda).
the flow
1) I read all the orders from the sql server tables that is not processed
2) then I need to divide the orders into two sets
- set 1 orders with bundle kit( 1 order with several suborders)
- set 2 is just orders with no bundle kit
3) then after each order is processed I need to update the isprocessed sql field to 1
1) code for reading all orders
Frmmain.vb
dt = WebDatabase.GetAllOrdersFromDatabase()**'this method is below**
For Each drow In dt.Rows
If CDbl(WinDSSStoreNumber) = 123 Or CDbl(WinDSSStoreNumber) = 124 Then
' Store 123 and 124 = customer service - only orders with qualifying source codes
my question is:
the above for each checks if the store is 123 or 124 but now I want to implement another for each loop that reads all the InvoiceHeader_Id that the second field in the datatable and then check if it has a bundle kit or not if it does then process it and update the isprocessed field second last in the datatable else process the orders without any bundle kit and update isprocessed for those as well. please any help is generously appreciated, please ask me any questions in the below comment before marking my question down.
WebData.vb
Public Function GetAllOrdersFromDatabase() As DataTable
DrivePath = "C:\Users\somjething\Documents\files\somefiles\"
Dim ds As DataTable = Nothing
WinDSS.connectionString = ConfigurationManager.AppSettings("WinDSS_Connection").Replace("%DrivePath%", DrivePath)
ds = WinDSS.GetSysMst()
If ds.Rows.Count > 0 Then
WinDSSStoreNumber = ds.Rows(0)("store_no")
End If
Dim dt As New DataTable()
Dim conn As New SqlConnection(ConfigurationManager.AppSettings("WebData_Connection") & ConfigurationManager.AppSettings("WebDataSource"))
Dim cmd As SqlCommand
Dim da As New SqlDataAdapter
conn.Open()
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText= SELECT InvoiceDetail_Id, InvoiceHeader_Id, ActualFreightCharge, AmountCollected,
ChargedActualFreight, CollectedExternally, CollectedThroughAR, DateInvoiced, InvoiceNo,
InvoiceType, LineSubTotal, MasterInvoiceNo, OrderInvoiceKey, Reference1, TotalAmount,
TotalTax, isprocessed, storetoprocess
FROM dbo.InvoiceHeader
WHERE (isprocessed = 0) AND (storetoprocess = N'123')
da.SelectCommand = cmd
da.Fill(dt)
conn.Close()
Return dt
End Function
Additoinal info
This is the information given to me by my manager:
loop throught each below
SELECT InvoiceDetail_Id, InvoiceHeader_Id, ActualFreightCharge, AmountCollected,
ChargedActualFreight, CollectedExternally, CollectedThroughAR, DateInvoiced, InvoiceNo,
InvoiceType, LineSubTotal, MasterInvoiceNo, OrderInvoiceKey, Reference1, TotalAmount,
TotalTax, isprocessed, storetoprocess
FROM dbo.InvoiceHeader WHERE (isprocessed = 0) AND (storetoprocess = N'195')
Use the above InvoiceHeader_Id to loop throught all of the order information. Process each Bundle (Kit/)
SELECT InvoiceHeader_Id, LineDetails_Id, LineDetail_Id, OrderLine_Id, GiftFlag, [References],
GiftWrap, IsBundleParent, KitCode, KitQty, LevelOfService, LineSeqNo, LineType,
MaxLineStatus, MaxLineStatusDesc, MinLineStatus, MinLineStatusDesc, MinShipByDate,
OpenQty, OrderHeaderKey, OrderLineKey, OrderedQty, OriginalOrderedQty, OtherCharges,
OverallStatus, PipelineKey, PrimeLineNo, ReceivingNode, RemainingQty, ReqCancelDate,
ReqDeliveryDate,
ReqShipDate, SCAC, ScacAndService, ScacAndServiceKey, ShipNode, ShipToID, ShipToKey,
StatusQuantity, SubLineNo, SubstituteItemID, isprocessed
FROM dbo.OrderLine
WHERE (isprocessed = 0) AND (InvoiceHeader_Id = 13) AND (IsBundleParent = 'Y')
ORDER BY PrimeLineNo, SubLineNo
For each record in the above list query below and add as Zero (0) dollar amount. The cost is associated with the information above record (you may have to query tables to ge the values)
Get the OrderLineKey from the above record and query this below to get the associated sub items.
SELECT TOP (100) PERCENT dbo.BundleParentLine.InvoiceHeader_Id AS BPL_InvoiceHeader_Id,
dbo.BundleParentLine.LineDetails_Id AS BPL_LineDetails_Id, dbo.BundleParentLine.LineDetail_Id AS BPL_LineDetail_Id, dbo.BundleParentLine.OrderLine_Id AS BPL_OrderLine_Id, dbo.BundleParentLine.BundleParentLine_id, dbo.BundleParentLine.SubLineNo AS BPL_SubLineNo, dbo.BundleParentLine.PrimeLineNo AS BPL_PrimeLineNo, dbo.BundleParentLine.OrderLineKey AS BPL_OrderLineKey, dbo.OrderLine.*
FROM dbo.BundleParentLine INNER JOIN dbo.OrderLine ON dbo.BundleParentLine.OrderLine_Id = dbo.OrderLine.OrderLine_Id AND dbo.BundleParentLine.LineDetail_Id = dbo.OrderLine.LineDetail_Id AND dbo.BundleParentLine.LineDetails_Id = dbo.OrderLine.LineDetails_Id AND dbo.BundleParentLine.InvoiceHeader_Id = dbo.OrderLine.InvoiceHeader_Id
WHERE (dbo.BundleParentLine.OrderLineKey = N'76873264832') AND (dbo.BundleParentLine.InvoiceHeader_Id = 13) AND (dbo.BundleParentLine.LineDetails_Id = 6) AND (dbo.OrderLine.isprocessed = 0)
ORDER BY BPL_PrimeLineNo, BPL_SubLineNo
After Processed, set isprocessed = 1
Use the above InvoiceHeader_Id to loop throught all of the order information
SELECT InvoiceHeader_Id, LineDetails_Id, LineDetail_Id, OrderLine_Id, GiftFlag, [References],
GiftWrap, IsBundleParent, KitCode, KitQty, LevelOfService, LineSeqNo,
LineType,
MaxLineStatus, MaxLineStatusDesc, MinLineStatus, MinLineStatusDesc, MinShipByDate,
OpenQty, OrderHeaderKey, OrderLineKey, OrderedQty,
OriginalOrderedQty,
OtherCharges, OverallStatus, PipelineKey, PrimeLineNo, ReceivingNode, RemainingQty,
ReqCancelDate, ReqDeliveryDate, ReqShipDate, SCAC,
ScacAndService,
ScacAndServiceKey, ShipNode, ShipToID, ShipToKey, StatusQuantity,
SubLineNo, SubstituteItemID, isprocessed
FROM dbo.OrderLine
WHERE (isprocessed = 0) AND (InvoiceHeader_Id = 13) AND (IsBundleParent <> 'Y')
ORDER BY PrimeLineNo, SubLineNo
After Processed, set isprocessed = 1
This is not an answer but I want to pose this to prompt you for some clarification and it's not practical in the comments.
First, close visual studio and open SQL Server Management Studio and connect to the database
We'll build some select statements to get the data back and then we can think about an UPDATE statement
This first query you posted gives you the unprocessed headers for store 195 (straight from your post). I don't know if you want to do this for all stores or not. Paste it into SSMS and run it
SELECT H.*
FROM dbo.InvoiceHeader H
WHERE H.isprocessed = 0 AND H.storetoprocess = N'195'
Now, this second query gives you the unprocessed lines against that header that have IsBundleParent='Y'.
Look! No loops!
SELECT H.*, L.*
FROM dbo.InvoiceHeader H
INNER JOIN
dbo.OrderLine L
ON L.InvoiceHeader_Id = H.InvoiceHeader_Id
WHERE H.isprocessed = 0 AND H.storetoprocess = N'195'
AND L.isprocessed = 0 AND L.IsBundleParent = 'Y'
Then in your explanation you have For each record in the above list query below and add as Zero (0) dollar amount which makes no sense to me so perhaps you could clarify
Now we'll add the third query in which adds BundleParentLine (which does have inner joins in it already, but it's a pretty strange list of join fields)
SELECT H.*, L.*, BPL.*
FROM dbo.InvoiceHeader H
INNER JOIN
dbo.OrderLine L
ON L.InvoiceHeader_Id = H.InvoiceHeader_Id
INNER JOIN
dbo.BundleParentLine BPL
ON BPL.OrderLine_Id = L.OrderLine_Id
AND BPL.LineDetail_Id = L.LineDetail_Id
AND BPL.LineDetails_Id = L.LineDetails_Id
AND BPL.InvoiceHeader_Id = L.InvoiceHeader_Id
WHERE H.isprocessed = 0 AND H.storetoprocess = N'195'
AND L.isprocessed = 0 AND L.IsBundleParent = 'Y'
Then in your explanation you have After Processed, set isprocessed = 1, but what is 'processed' here? Is it just setting it to processed in the table?
To do that you just write an UPDATE statement. Here's one way to do that to update just the header (don't run it though until we understand what you're trying to do). Is the problem here that you want to set header and line to processed at the same time?
UPDATE InvoiceHeader
SET Processed = 1
WHERE isprocessed = 0 AND storetoprocess = N'195'
The fourth query you have seems to account for the IsBundleParent <> 'Y' case
Again, we need to know what add as Zero (0) dollar amount and processed means to go any further.

Why Is My Subtraction Result Incorrect?

select sum(l.coins) - sum(t.coins) as total
from luxx_getaway_2016_coins l
join thrive_rewards_redeemed t
on l.consid = t.guideid
where l.consid = 24969 and t.harvestyear = 1516
Hello all. I am attempting to grab an updated total using the query above. The problem I'm having is that the total of these sums totals out to well above what it should be. I'm unsure of what I'm doing wrong. We're using Azure SQL Database and I've used RazorSQL and SSMS 2012 to run this query with identical results. Any help is appreciated. Please feel free to ask for clarification.
A simple solution to your duplication problem:
Select
(select sum(l.coins)
from luxx_getaway_2016_coins l
where l.consid = 24969)
-
(select sum(t.coins)
from thrive_rewards_redeemed t
where t.guideid = 24969
and t.harvestyear = 1516)
For the more general case:
; With A as (select consid, sum(l.coins) as TotA
from luxx_getaway_2016_coins l
group by consid)
, B as (select guideid, sum(t.coins) as TotB
from thrive_rewards_redeemed t
where t.harvestyear = 1516
group by guideID)
Select a.consid, TotA - TotB as Total
from A
inner join B
on a.Consid = b.GuideID

Show count in SSRS using SQL Server

Below is my sql query
USE AdventureWorks2012
Select EDH.*,
case when EDH.DepartmentID between 1 and 5 then 'DEPT-A'
when EDH.DepartmentID between 5 and 9 then 'DEPT-B'
when EDH.DepartmentID between 9 and 30 then 'DEPT-C' end as [DEPT TYPE]---, count(EDH.DepartmentID)
from HumanResources.EmployeeDepartmentHistory EDH
left outer join HumanResources.Employee EM on EM.BusinessEntityID = EDH.BusinessEntityID
group by EDH.DepartmentID, EDH.BusinessEntityID, EDH.ShiftID, EDH.StartDate, EDH.EndDate, EDH.ModifiedDate
I'm bringing the Dept Type column either as Dept-A, B or C based on Case when Condition on Department ID.
Now in the SSRS report I want to show the count of the Department Column in the footer such as
Dept Count[A/B/C]: 49/195/46
How to show the count in the report? Should I modify the query or there is some change required in the report
You can use an expression like:
="Dept Count [A/B/C]: "
& Sum(IIf(Fields!DeptType.Value = "DEPT-A", 1, 0)) & "/"
& Sum(IIf(Fields!DeptType.Value = "DEPT-B", 1, 0)) & "/"
& Sum(IIf(Fields!DeptType.Value = "DEPT-C", 1, 0))
This will work as you have a set amount of department types. Use a conditional Sum with IIf to get the numbers in each account.
Works on some simplified data:

Resources