SQL Server 2008 priority on different columns - sql-server-2008

I have to clean data based on the following criteria. I have 3 columns PhoneNumber, phoneType and phoneStatus. The order of priority is as follows:
Phone Status = Do Not Call
Phone Type = Work Cell-No Consent, Cell - No Consent, Work Cell, Cell, Cell w/Permission, Work, Spouse Work, Home, Spouse Home, Third party Number, Fax
Phone Status = Bad, Good, Unknown.
I am trying to use row_number() but it didn't work.
For example if I have
PhoneTypeID PhoneStatusID PhoneNumber
------------------------------------------
Work Unknown 9999999999
Cell Do not call 9999999999
I want to delete the first row
Thanks in advance!

Related

SumIIF Access Query

I am struggling to get the desired results i need using an Access query, and was wondering if what i was looking to do was actually achievable in one query, or whether i would need two queries and then export to Excel and interrogate the results there.
I've a table with a number of columns, i am specifically looking at three columns
Row Type - this will either be populated with A or U
Account Number - there will be potentially multiple instances of account number within the table. Although only once against row type "A", and multiple on row type "U"
Value - a currency field. At Account number level, the sum of "U" row, should equal the "A" value
I am looking to produce a query that will list three things.
[Account Number]
Sum of [Value] when [RowType] = "U"
[Value] when [RowType] = "A"
Would i need to create a new column in my table to generate a value for the requirement "Sum of Value when 'U')
I've tried
SUM(IIF([ROWTYPE]='U',[Value],0)) - but that doesn't seem to work.
I've also tried to use the builder within the Query to replicate the same, but again that also doesn't seem to work.
If all else fails i'm content to have to run two queries in Access and then join Excel, but i tihnk for my own learning and knowledge it would be good to know if what i am trying to do is possible.
I was hoping this is possible to compile in Access, but my knowledge of the application is seriously lacking, and despite looking on the MS Access support pages, and also some of the response on the StackOverflow forums, i still can't get my head around what i need to do.
Example of the data
Row Type
Account ID
Value
A
123456789
50.00
U
123456789
30.00
U
123456789
20.00
A
987654321
100.00
U
987654321
80.00
U
987654321
20.00
The data has been loaded into Access, table called "TEST"
This is the SQL i've got, but doesn't give me the desired results.
SELECT [TEST].[ROW TYPE], SUM([TEST].[VALUE]) AS [TEST].[ACCOUNT ID]
FROM [TEST]
GROUP BY [TEST].[ROW TYPE], [TEST].[ACCOUNTID]
When the query generates, would hope to see two rows, one for each account number.
Three row -
Account Number
Sum Value (where row is U)
Value (Where row is A)
I currently get 4 rows in the query. Two results for each account number, one result is the Value when Row Type = A, the other when Row Type = U.
I guess this is what you are after:
SELECT
[Account ID],
Sum(IIf([Row Type]="A",[Value],0)) AS A,
Sum(IIf([Row Type]="U",[Value],0)) AS U
FROM
TEST
GROUP BY
[Account ID];
Output:
Account ID
A
U
123456789
50,00
50,00
987654321
100,00
100,00

How to filter based on a certain column in SQL?

I have the following problem: I want to filter a list of clients based on their phone number.
My actual output:
id firstname lastname phonenumber creation date
1 client client 664433 2020/01/02
2 client client 664433 2020/01/02
3 client client 664432 2020/01/02
4 client client 669433 2020/01/02
5 client client 964433 2020/01/02
6 client client 664033 2020/01/02
As you can see, there are phone numbers duplicated.
My desired output should be:
id firstname lastname phonenumber creation date
1 client client 664433 2020/01/02
2 client client 664432 2020/01/02
3 client client 669433 2020/01/02
4 client client 964433 2020/01/02
5 client client 664033 2020/01/02
Here is the code I'm using in order to identify these duplicated numbers and remove them from my output:
select
cc.id ,
cc."FirstName",
cc."LastName",
cc."PhoneNumber" as phone_number,
case when cc."PhoneNumber" is not null count(cc."PhoneNumber") else 0,
cc."CreationDate"
from souscritootest.public.clients_crm cc
having count(cc."PhoneNumber") = 1
;
The problem is that I'm getting this feedback from the IDE: SQL Error [42601]: ERROR: syntax error at or near "count" Position: 128
What I want to do is create a column with the case when to tag with a 1 if it's duplicated and 0 if it's not duplicated.
Thanks!
To get a distinct list of values, you just need to use the DISTINCT keyword.
SELECT DISTINCT cc.Id...
Though this is the correct answer to your question, I suspect that the client names are not all "client client" with the same creation date. Which means you probably have some clients with the same phone number. In that case, which client would you want to show? Take a look at this example data to get a better grasp on the issue:
id firstname lastname phonenumber creation date
1 Joel Foo 664433 2020/01/02
2 John Bar 664433 2020/01/03
3 Angelo Foobar 664432 2020/01/04
In this case we would want to remove the duplicate phone number 664433, but which name would we want to show for the number: Joel or John?
Removing duplicates in the query might solve your problem, but could produce a bigger one later. I would recommend not allowing duplicate phone numbers in the first place if the requirements are to not have them.

SQL into Table Multiple queries same column

I am trying to create a web based report to show the response of certain advertisements.
$sql1 = "
SELECT date
, source
, source_desc
, COUNT(ordernumber) count
, SUM(ordervalue) value
, type
FROM dailystats
WHERE client = '$client2'
AND event <> 'B02'
AND date BETWEEN '$start' AND '$end'
GROUP
BY source
ORDER
BY source;
";
This works fine for my table to show total values, but I want to break it down further. I currently have SOURCE {source}, DESCRIPTION {source_desc}, TOTAL ORDERS {count}, TOTAL ORDER VALUE {value}, as my headers which are populated by the above fields.
I want, as well as the current totals, to include further columns when the field "TYPE" is "P", "T" and "E". I want this to leave me with data to fill new headers (when I put them into the table) consisting of SOURCE, DESCRIPTION, WEB ORDERS, WEB ORDER VALUE, PHONE ORDERS, PHONE ORDER VALUE, POST ORDERS, POST ORDER VALUE, TOTAL ORDERS, TOTAL ORDER VALUE.
I need to create the data for the new headers, so WEB ORDERS will give me the total orders with the TYPE "E". On its own this would be something like COUNT(ordernumber) count where type = "E", but I need multiple of these and I cannot get it to work.
It currently looks like this :
|Source|Source Description|Total Orders|Total Order Value|
|DM1 |Daily Mail 1 |500 |5,000 |
I want to retain this information, but add in as described above, to look like this.
|Source|Source Description|Web Orders|Web Order Value|Post Orders|Post Order Value|Mail Orders|Mail Order Value|Total Orders|Total Order Value|
|DM1 |Daily Mail 1 |100 |1,000 |300 |3,000 |100 |1,000 |500 |5,000 |
I hope I have explained my problem adequately.
use group_concat(type) as type in your code.
(if it is wrong sry. pls explain it clear)
I want this to leave me with headers (when I put them into the table) of SOURCE, DESCRIPTION, WEB ORDERS, WEB ORDER VALUE, PHONE ORDERS, PHONE ORDER VALUE, POST ORDERS, POST ORDER VALUE, TOTAL ORDERS, TOTAL ORDER VALUE.
If i understand correctly you want to add headers to your result ? this should be done by:
SELECT column_name(s)
FROM table_name AS alias_name;

Interactive sorting In SSRS on Values - Matrix report

I want a interactive sorting in SSRS matrix report. From database we are getting 3 columns -PrimaryKey,Columns and Value.
We are grouping rows by Primary Key and grouping column by Columns and use Value as data.
My Matrix Report -
ID [Columns]
[Primary Key] Values
Output of the Matrix report -
ID FirstName MiddleName Lastname
1 Rajiv Jha Sharma
2 Prem Kumar Bose
3 Usha Shamila Praveena
I am able to use the interactive sorting on ID because ID is group by rows but I want to use the interactive sorting on dynamic cloumns values like FirstName,MiddleName and LastName.
Expected result when we interactive sort on Lastname
ID FirstName MiddleName Lastname
2 Prem Kumar Bose
3 Usha Shamila Praveena
1 Rajiv Jha Sharma
Thanks for any Help.
Are you using the report wizard to build this? You should be able apply the interactive sort using the properties menu on the column groups.
By adding an interactive sort button to a column header you can allow a user to click the column header and sort the parent group rows in a table or matrix by the value displayed in that column. The order of child groups remains unchanged.
To add an interactive sort button to a column header to sort groups:
In a table or matrix on the report design surface, right-click the text box in the column header for the group to which you want to add an interactive sort button.
Click Text Box Properties.
Click Interactive Sort.
Select Enable interactive sort on this text box.
In Sort, click Groups.
From the drop-down list, select the name of the group that you are sorting. For groups based on simple group expressions, the Sort by value is populated with group expression.
For more info, see this article: http://technet.microsoft.com/en-us/library/cc627509(v=sql.100).aspx
Quite an old question, but I stumbled upon similar problem recently.
Though SSRS does not allow you to add interactive sorting on dynamic columns in a matrix, you can simulate similar behaviour. I've figured out a method, which require the report to fire itself (through go to report action) sorted on desired column.
I will use a bit more complicated example to show the full functionality of this solution.
Imagine an online bookstore, which would like a report showing their customers (rows), number of books (values) and total value of books (values), which they bought, by category – Fiction/NonFiction in my example (columns). Of course they want to see their best customers, so the sort will be descending.
Example data that we are getting from the database:
UserID Columns BooksCount BooksValue
AliBaba Fiction 2 25.96
AliBaba NonFiction 4 112.00
ThomasJefferson Fiction 3 36.83
ThomasJefferson NonFiction 1 46.80
BillCosby Fiction 10 536.47
BillCosby NonFiction 2 26.87
The report will look like this:
[Columns]
Books Count Books Value
[UserID] Values Values
I would like the report to be able to sort by “Books Count” or “Books Value” for any Column. Here are the steps to follow:
You need to add parameters that will store the name of the column to sort on - #SortColumn and the metric name (counts or values) to sort on - #SortMetric.
Go to “Books Count” textbox and add action "Go to report" specifying the same report. Add #SortColumn parameter with a value from [Columns] field in the underlying dataset. Add #SortMetric parameter with value set to “BooksCount”. Similar for “Books Value” textbox.
You can adjust the column header text with following expression, which will show the user on which column data is sorted:
= IIf( Parameters!SortColumn.Value=Fields!Columns.Value And Parameters!SortMetric.Value = "BooksCount" ," ^","")
This was for “Books Count”, you can add similar for “Books Amount”
Finally the magic that happens on the database site. Source table is named [Sales]. Apart from the sorting, below code allows to select only top N rows if your dataset is larger.
You can create a dataset using this code or better create a stored procedure. And join report parameters with dataset parameters.
DECLARE #TopN INT = 50
;WITH Users_Sorted AS
(
SELECT
UserID
,ROW_NUMBER() OVER (ORDER BY
CASE #SortMetric
WHEN 'BooksCount' THEN Sales.BooksCount
WHEN 'BooksValue' THEN Sales.BooksValue
END DESC) AS ROWNO
FROM Sales
WHERE
Sales.Columns = #SortColumn
)
,Sales_MAIN AS
(
SELECT
Sales.UserID
,Sales.Columns
,Sales.BooksCount
,Sales.BooksValue
,ISNULL(Users_Sorted.ROWNO,
ROW_NUMBER () OVER (PARTITION BY Sales.Columns ORDER BY Sales.UserID ASC)
) AS ROWNO
FROM Sales
LEFT JOIN Users_Sorted ON Sales.UserID = Users_Sorted.UserID
)
SELECT * FROM Sales_MAIN WHERE ROWNO <= #TopN ORDER BY ROWNO

MySQL query does count then display additional data

This current query works great and gives me a count of how many times and office occurs in the table for each record and the office name. How do I expand this query to first display the Office and Count like it currently does and THEN displays colums lastName, Phone underneath the count of each record that matched the Office and then moves onto the next Office and Office(Count) and displays those lastname, Phone records and so forth? Is that possible in MySQL?
SELECT Office, COUNT(Office) AS c
FROM Active
GROUP BY Office
HAVING COUNT(Office) >= 5 ORDER BY c DESC
Example:
Office1 | 2
Office1 | lastName | Phone
Office1 | lastName | Phone
Office2 | 3
Office2 | lastName | Phone
Office2 | lastName | Phone
Office2 | lastName | Phone
No you cannot do that. Your best bet would be UNION, but you must have identical number of columns and column types, which doesn't match your criteria.
Why don't you try
SELECT Office, lastName, Phone FROM Active ORDER BY Office
and in your programming language, parse the rows and use a counter variable to count identical Office records, and build your own table.
Edit: You say it's for exporting directly to a spreadsheet. You could do this in two queries: Do your count() query, and then do the query I have above. Export the two results and mix them in a spreadsheet as you need. Hey, it gets the job done.
You can try to use MySQL's UNION, but the number of the columns, and the column names would have to be identical.
Overall this seems like a wrong approach. Try rethinking your logic where you don't need this sort of output.
I would suggest receiving just the lastname and phone, and caching the results, then parsing them. The COUNT(*) is technically redundant information since the number of rows with identical Office already describes that.